/**
 * 简单的后端测试服务器
 * 用于测试前端API连接
 */

import express from 'express'
import cors from 'cors'
const app = express()
const PORT = 8080

// 中间件
app.use(cors({
  origin: ['http://localhost:5173', 'http://localhost:5175'],
  credentials: true
}))
app.use(express.json())

// 请求日志中间件
app.use((req, res, next) => {
  console.log(`${new Date().toISOString()} - ${req.method} ${req.path}`)
  next()
})

// 健康检查接口
app.get('/api/health', (req, res) => {
  res.json({
    code: 200,
    message: '后端服务运行正常',
    data: {
      status: 'healthy',
      timestamp: new Date().toISOString(),
      version: '1.0.0',
      service: '商户端后端服务'
    }
  })
})

// 测试账号数据
const testAccounts = [
  {
    username: 'admin',
    password: '123456',
    userInfo: {
      id: 1,
      username: 'admin',
      name: '测试商户A',
      role: 'merchant',
      phone: '13800138000',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  },
  {
    username: '13900139000',
    password: '123456',
    userInfo: {
      id: 2,
      username: '13900139000',
      name: '测试商户B',
      role: 'merchant',
      phone: '13900139000',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  },
  {
    username: 'merchant01',
    password: '123456',
    userInfo: {
      id: 3,
      username: 'merchant01',
      name: '测试商户C',
      role: 'merchant',
      phone: '13700137000',
      avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'
    }
  }
]

// ==================== 认证相关接口 ====================

// 登录接口
app.post('/api/auth/login', (req, res) => {
  const { username, password } = req.body

  console.log('登录请求:', { username, password })

  // 查找匹配的测试账号
  const account = testAccounts.find(acc =>
    acc.username === username && acc.password === password
  )

  if (account) {
    res.json({
      code: 200,
      message: '登录成功',
      data: {
        token: 'test-jwt-token-' + Date.now(),
        userInfo: account.userInfo
      }
    })
  } else {
    res.status(401).json({
      code: 401,
      message: '用户名或密码错误',
      data: null
    })
  }
})

// 注册接口
app.post('/api/auth/register', (req, res) => {
  const { phone, password, verifyCode, agreement } = req.body

  console.log('注册请求:', { phone, password, verifyCode, agreement })

  // 验证必填字段
  if (!phone || !password || !verifyCode) {
    return res.status(400).json({
      code: 400,
      message: '请填写完整的注册信息',
      data: null
    })
  }

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    return res.status(400).json({
      code: 400,
      message: '请输入正确的手机号码',
      data: null
    })
  }

  // 验证密码强度
  if (password.length < 8 || !/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/.test(password)) {
    return res.status(400).json({
      code: 400,
      message: '密码必须包含大小写字母和数字，长度不少于8位',
      data: null
    })
  }

  // 验证验证码（测试环境固定为123456）
  if (verifyCode !== '123456') {
    return res.status(400).json({
      code: 400,
      message: '验证码错误',
      data: null
    })
  }

  // 验证协议同意
  if (!agreement) {
    return res.status(400).json({
      code: 400,
      message: '请阅读并同意商家入驻协议',
      data: null
    })
  }

  // 检查手机号是否已注册
  const existingAccount = testAccounts.find(acc => acc.username === phone)
  if (existingAccount) {
    return res.status(400).json({
      code: 400,
      message: '该手机号已注册，请直接登录',
      data: null
    })
  }

  // 创建新账号
  const newAccount = {
    username: phone,
    password: password,
    userInfo: {
      id: Date.now(),
      username: phone,
      phone: phone,
      nickname: `商户${phone.slice(-4)}`,
      avatar: '',
      email: '',
      status: 'pending', // pending: 待审核, approved: 已审核, rejected: 已拒绝
      createTime: new Date().toISOString(),
      lastLoginTime: null,
      merchantInfo: {
        businessName: '',
        businessType: '',
        businessLicense: '',
        contactPerson: '',
        contactPhone: phone,
        businessAddress: '',
        serviceArea: '',
        authStatus: 'pending'
      }
    }
  }

  // 添加到测试账号列表
  testAccounts.push(newAccount)

  res.json({
    code: 200,
    message: '注册成功，请登录',
    data: {
      userId: newAccount.userInfo.id,
      phone: phone,
      status: 'pending'
    }
  })
})

// 发送验证码接口
app.post('/api/auth/verify-code', (req, res) => {
  const { phone, type } = req.body

  console.log('发送验证码请求:', { phone, type })

  // 验证手机号格式
  if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
    return res.status(400).json({
      code: 400,
      message: '请输入正确的手机号码',
      data: null
    })
  }

  // 模拟发送验证码
  console.log(`向 ${phone} 发送验证码: 123456 (类型: ${type})`)

  res.json({
    code: 200,
    message: '验证码发送成功',
    data: {
      phone: phone,
      type: type,
      expireTime: new Date(Date.now() + 5 * 60 * 1000).toISOString(), // 5分钟过期
      code: '123456' // 测试环境返回验证码，生产环境不应返回
    }
  })
})

// 重置密码接口
app.post('/api/auth/reset-password', (req, res) => {
  const { phone, password, verifyCode } = req.body

  console.log('重置密码请求:', { phone, password, verifyCode })

  // 验证必填字段
  if (!phone || !password || !verifyCode) {
    return res.status(400).json({
      code: 400,
      message: '请填写完整的重置信息',
      data: null
    })
  }

  // 验证手机号格式
  if (!/^1[3-9]\d{9}$/.test(phone)) {
    return res.status(400).json({
      code: 400,
      message: '请输入正确的手机号码',
      data: null
    })
  }

  // 验证验证码（测试环境固定为123456）
  if (verifyCode !== '123456') {
    return res.status(400).json({
      code: 400,
      message: '验证码错误',
      data: null
    })
  }

  // 查找账号
  const account = testAccounts.find(acc => acc.username === phone)
  if (!account) {
    return res.status(404).json({
      code: 404,
      message: '该手机号未注册',
      data: null
    })
  }

  // 更新密码
  account.password = password

  res.json({
    code: 200,
    message: '密码重置成功，请登录',
    data: {
      phone: phone,
      resetTime: new Date().toISOString()
    }
  })
})

// 获取用户信息接口
app.get('/api/auth/info', (req, res) => {
  // 从请求头获取token（实际应用中需要验证token）
  const token = req.headers.authorization

  if (!token) {
    return res.status(401).json({
      code: 401,
      message: '未登录或登录已过期',
      data: null
    })
  }

  // 模拟返回用户信息（实际应用中应该从token解析用户信息）
  const userInfo = testAccounts[0].userInfo // 返回第一个测试账号的信息

  res.json({
    code: 200,
    message: '获取用户信息成功',
    data: userInfo
  })
})

// 退出登录接口
app.post('/api/auth/logout', (req, res) => {
  // 实际应用中应该清除服务端的token记录
  res.json({
    code: 200,
    message: '退出登录成功',
    data: null
  })
})

// 检查用户名是否可用
app.get('/api/auth/check-username', (req, res) => {
  const { username } = req.query

  const exists = testAccounts.some(acc => acc.username === username)

  res.json({
    code: 200,
    message: '检查完成',
    data: {
      available: !exists,
      username: username
    }
  })
})

// 检查手机号是否已注册
app.get('/api/auth/check-phone', (req, res) => {
  const { phone } = req.query

  const exists = testAccounts.some(acc => acc.userInfo.phone === phone)

  res.json({
    code: 200,
    message: '检查完成',
    data: {
      registered: exists,
      phone: phone
    }
  })
})

// 获取商家信息
app.get('/api/merchant/info', (req, res) => {
  res.json({
    code: 200,
    message: '获取商家信息成功',
    data: {
      // 基本信息
      id: 12345,
      merchantCode: 'M202412210001',
      avatar: 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
      name: '洗护专家店铺',
      type: '企业商户',
      status: '已认证',

      // 联系信息
      phone: '13800138000',
      email: 'merchant@example.com',
      contactPerson: '张三',
      contactPhone: '13800138000',

      // 时间信息
      joinTime: '2023-01-15',
      lastLoginTime: '2024-12-21 10:30:00',
      certificationTime: '2023-01-20 10:30:00',

      // 地址信息
      address: '北京市朝阳区建国路88号',
      fullAddress: '北京市朝阳区建国路88号SOHO现代城A座1001室',
      province: '北京市',
      city: '北京市',
      district: '朝阳区',

      // 商家资质
      creditScore: 0, // 信用分数：0分
      businessLicense: '已上传',
      licenseNo: '91110000123456789X',
      legalPerson: '张三',
      shopName: '洗护专家店铺',
      establishDate: '2020-01-15',
      businessTermStart: '2020-01-15',
      businessTermEnd: '2040-01-15',

      // 服务信息
      serviceTypes: ['洗衣服', '洗鞋', '洗包包', '洗被子', '洗车', '上门清洗'],
      serviceCount: 0,
      totalOrders: 0,
      totalRevenue: 0,

      // 银行卡信息
      bankCards: [
        {
          id: 'card_001',
          cardNumber: '6225881234567890',
          bankName: '中国工商银行',
          cardType: '储蓄卡',
          holderName: '张三',
          isDefault: true,
          status: 'verified',
          bindTime: '2023-01-20'
        }
      ],

      // 认证信息
      certification: {
        shopName: '洗护专家店铺',
        shopType: 'enterprise',
        contactName: '张三',
        contactPhone: '13800138000',
        region: ['北京市', '北京市', '朝阳区'],
        address: '建国路88号SOHO现代城A座1001室',
        licenseNo: '91110000123456789X',
        legalPerson: '张三',
        establishDate: '2020-01-15',
        businessTerm: ['2020-01-15', '2040-01-15'],
        serviceTypes: ['洗衣服', '洗鞋', '洗包包', '洗被子'],
        businessScope: '洗衣、洗鞋、包包护理、被子清洗等服务',
        licenseImage: 'https://example.com/license.jpg',
        idCardImage: 'https://example.com/idcard.jpg'
      },

      // 统计信息
      statistics: {
        todayOrders: 0,
        monthOrders: 0,
        totalCustomers: 0,
        averageRating: 0,
        responseRate: 0,
        completionRate: 0
      }
    }
  })
})

// 更新商家信息
app.put('/api/merchant/info', (req, res) => {
  const { avatar, name, phone, email, address } = req.body

  res.json({
    code: 200,
    message: '商家信息更新成功',
    data: {
      avatar,
      name,
      phone,
      email,
      address,
      updateTime: new Date().toISOString()
    }
  })
})

// 更新密码
app.put('/api/merchant/password', (req, res) => {
  const { oldPassword, newPassword } = req.body

  // 模拟密码验证
  if (oldPassword === '123456') {
    res.json({
      code: 200,
      message: '密码修改成功',
      data: {
        updateTime: new Date().toISOString()
      }
    })
  } else {
    res.json({
      code: 400,
      message: '原密码错误',
      data: null
    })
  }
})

// 商户概览数据
app.get('/api/merchant/overview', (req, res) => {
  res.json({
    code: 200,
    message: '获取成功',
    data: {
      todayRevenue: 2580.50,
      revenueCompare: 12.5,
      todayOrders: 45,
      ordersCompare: 8.3,
      completionRate: 95.2,
      completionRateCompare: 2.1,
      satisfactionRate: 88.6,
      satisfactionCompare: 1.8
    }
  })
})

// 待处理事项
app.get('/api/merchant/pending-tasks', (req, res) => {
  res.json({
    code: 200,
    message: '获取成功',
    data: {
      pendingOrders: 8,
      pendingPickup: 12,
      processing: 15,
      pendingDelivery: 6,
      pendingReview: 3,
      pendingServiceAudit: 2
    }
  })
})

// 销售趋势数据
app.get('/api/merchant/sales-trend', (req, res) => {
  const { type = 'week' } = req.query
  
  let dates, amounts, orders
  
  if (type === 'week') {
    dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    amounts = [1200, 1800, 2200, 1900, 2500, 3200, 2800]
    orders = [15, 22, 28, 24, 32, 41, 35]
  } else {
    dates = ['1日', '2日', '3日', '4日', '5日', '6日', '7日']
    amounts = [800, 1200, 1500, 1100, 1800, 2100, 1900]
    orders = [10, 15, 19, 14, 23, 27, 24]
  }
  
  res.json({
    code: 200,
    message: '获取成功',
    data: { dates, amounts, orders }
  })
})

// 分类销售数据
app.get('/api/merchant/category-sales', (req, res) => {
  res.json({
    code: 200,
    message: '获取成功',
    data: []
  })
})

// 热销商品数据
app.get('/api/merchant/hot-goods', (req, res) => {
  res.json({
    code: 200,
    message: '获取成功',
    data: []
  })
})

// 仪表板相关接口
app.get('/api/dashboard/overview', (req, res) => {
  res.json({
    code: 200,
    message: '获取概览数据成功',
    data: {
      todayRevenue: 0,
      revenueCompare: 0,
      todayOrders: 0,
      ordersCompare: 0,
      completionRate: 0,
      completionRateCompare: 0,
      satisfactionRate: 0,
      satisfactionCompare: 0
    }
  })
})

app.get('/api/dashboard/pending-tasks', (req, res) => {
  res.json({
    code: 200,
    message: '获取待处理事项成功',
    data: {
      pendingOrders: 0,
      pendingPickup: 0,
      processing: 0,
      pendingDelivery: 0,
      pendingReview: 0,
      pendingServiceAudit: 0
    }
  })
})

app.get('/api/dashboard/sales-trend', (req, res) => {
  const { type = 'week' } = req.query
  let dates = []
  let amounts = []
  let orders = []

  // 根据类型返回不同的数据
  if (type === 'week') {
    dates = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
    amounts = [0, 0, 0, 0, 0, 0, 0]
    orders = [0, 0, 0, 0, 0, 0, 0]
  } else if (type === 'month') {
    dates = Array.from({length: 30}, (_, i) => `${i + 1}日`)
    amounts = Array.from({length: 30}, () => 0)
    orders = Array.from({length: 30}, () => 0)
  } else if (type === 'year') {
    dates = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    amounts = Array.from({length: 12}, () => 0)
    orders = Array.from({length: 12}, () => 0)
  }

  res.json({
    code: 200,
    message: '获取销售趋势成功',
    data: {
      dates,
      amounts,
      orders
    }
  })
})

app.get('/api/dashboard/category-sales', (req, res) => {
  res.json({
    code: 200,
    message: '获取分类销售数据成功',
    data: []
  })
})

app.get('/api/dashboard/hot-goods', (req, res) => {
  res.json({
    code: 200,
    message: '获取热销商品成功',
    data: []
  })
})

// 统计概览数据
app.get('/api/statistics/overview', (req, res) => {
  res.json({
    code: 200,
    message: '获取成功',
    data: {
      totalOrders: 0,
      orderTrend: 0,
      totalRevenue: 0,
      revenueTrend: 0,
      totalCustomers: 0,
      customerTrend: 0,
      satisfaction: 0,
      satisfactionTrend: 0
    }
  })
})

// 评价管理相关接口
// 获取评价统计
app.get('/api/reviews/stats', (req, res) => {
  res.json({
    code: 200,
    message: '获取评价统计成功',
    data: {
      good: 0,
      medium: 0,
      bad: 0,
      total: 0,
      avgScore: 0
    }
  })
})

// 获取评价列表
app.get('/api/reviews', (req, res) => {
  const { page = 0, size = 10, rating } = req.query

  res.json({
    code: 200,
    message: '获取评价列表成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 回复评价
app.post('/api/reviews/:id/reply', (req, res) => {
  const { id } = req.params
  const { content } = req.body

  res.json({
    code: 200,
    message: '回复发送成功',
    data: {
      id: parseInt(id),
      reply: content,
      replyTime: new Date().toISOString()
    }
  })
})

// 申诉评价
app.post('/api/reviews/:id/appeal', (req, res) => {
  const { id } = req.params
  const { reason } = req.body

  res.json({
    code: 200,
    message: '申诉提交成功',
    data: {
      id: parseInt(id),
      appealReason: reason,
      appealTime: new Date().toISOString(),
      status: 'pending'
    }
  })
})

// 获取回复模板
app.get('/api/reviews/reply-templates', (req, res) => {
  res.json({
    code: 200,
    message: '获取回复模板成功',
    data: []
  })
})

// 导出评价数据
app.get('/api/reviews/export', (req, res) => {
  // 模拟Excel文件
  const excelBuffer = Buffer.from('评价数据导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', 'attachment; filename=reviews.xlsx')
  res.send(excelBuffer)
})

// 获取评价分析
app.get('/api/reviews/analysis', (req, res) => {
  res.json({
    code: 200,
    message: '获取评价分析成功',
    data: {
      trends: [],
      keywords: [],
      satisfaction: 0
    }
  })
})

// 服务管理相关接口
// 获取服务列表
app.get('/api/services', (req, res) => {
  const { page = 0, size = 100, keyword, status, type } = req.query

  res.json({
    code: 200,
    message: '获取服务列表成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 获取服务统计
app.get('/api/services/stats', (req, res) => {
  res.json({
    code: 200,
    message: '获取服务统计成功',
    data: {
      total: 0,
      active: 0,
      pending: 0,
      draft: 0,
      approved: 0,
      rejected: 0,
      banned: 0,
      inactive: 0,
      totalOrders: 0,
      totalRevenue: 0,
      ordersTrend: 0,
      revenueTrend: 0
    }
  })
})

// 获取押金状态列表
app.get('/api/services/deposit/status', (req, res) => {
  res.json({
    code: 200,
    message: '获取押金状态成功',
    data: {
      LAUNDRY: false,
      SHOES: false,
      PET: false,
      BAG: false,
      BEDDING: false,
      CAR: false,
      HOME_CLEANING: false,
      PLUMBING: false
    }
  })
})

// 获取服务模板
app.get('/api/services/templates', (req, res) => {
  res.json({
    code: 200,
    message: '获取服务模板成功',
    data: []
  })
})

// 创建服务
app.post('/api/services', (req, res) => {
  res.json({
    code: 200,
    message: '服务创建成功',
    data: {
      id: Date.now(),
      ...req.body,
      status: 'DRAFT',
      createTime: new Date().toISOString()
    }
  })
})

// 更新服务
app.put('/api/services/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '服务更新成功',
    data: {
      id: parseInt(id),
      ...req.body,
      updateTime: new Date().toISOString()
    }
  })
})

// 删除服务
app.delete('/api/services/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '服务删除成功',
    data: {
      id: parseInt(id)
    }
  })
})

// 上架/下架服务
app.put('/api/services/:id/status', (req, res) => {
  const { id } = req.params
  const { status } = req.body

  res.json({
    code: 200,
    message: '服务状态更新成功',
    data: {
      id: parseInt(id),
      status: status
    }
  })
})

// 支付押金
app.post('/api/services/deposit/pay', (req, res) => {
  const { serviceType, amount } = req.body

  res.json({
    code: 200,
    message: '押金支付成功',
    data: {
      serviceType: serviceType,
      amount: amount,
      payTime: new Date().toISOString()
    }
  })
})

// 获取服务洞察数据
app.get('/api/services/insights', (req, res) => {
  res.json({
    code: 200,
    message: '获取服务洞察成功',
    data: {
      totalViews: 0,
      viewsTrend: 0,
      conversionRate: 0,
      conversionTrend: 0,
      avgOrderValue: 0,
      aovTrend: 0,
      customerSatisfaction: 0,
      satisfactionTrend: 0,
      topServices: [],
      customerProfile: {
        ageGroup: '',
        genderRatio: '',
        preference: '',
        activeTime: ''
      },
      suggestions: []
    }
  })
})

// 提现管理相关接口
// 获取余额信息
app.get('/api/withdrawal/balance', (req, res) => {
  res.json({
    code: 200,
    message: '获取余额信息成功',
    data: {
      availableBalance: 0,
      frozenBalance: 0,
      pendingBalance: 0,
      totalWithdrawn: 0
    }
  })
})

// 提交提现申请
app.post('/api/withdrawal/apply', (req, res) => {
  const { amount, method, account, accountName, remark } = req.body

  res.json({
    code: 200,
    message: '提现申请提交成功',
    data: {
      id: Date.now(),
      amount: amount,
      method: method,
      account: account,
      accountName: accountName,
      remark: remark,
      status: 'pending',
      createTime: new Date().toISOString()
    }
  })
})

// 获取提现记录
app.get('/api/withdrawal/records', (req, res) => {
  const { page = 0, size = 10, status } = req.query

  res.json({
    code: 200,
    message: '获取提现记录成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 取消提现申请
app.put('/api/withdrawal/cancel/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '提现申请已取消',
    data: {
      id: parseInt(id),
      status: 'cancelled',
      cancelTime: new Date().toISOString()
    }
  })
})

// 服务区域管理相关接口
// 获取服务区域列表
app.get('/api/service-areas', (req, res) => {
  const { page = 0, size = 10, keyword, status } = req.query

  res.json({
    code: 200,
    message: '获取服务区域列表成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 创建服务区域
app.post('/api/service-areas', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '服务区域创建成功',
    data: {
      id: Date.now(),
      ...data,
      status: 'enabled',
      createTime: new Date().toISOString()
    }
  })
})

// 更新服务区域
app.put('/api/service-areas/:id', (req, res) => {
  const { id } = req.params
  const data = req.body

  res.json({
    code: 200,
    message: '服务区域更新成功',
    data: {
      id: parseInt(id),
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 删除服务区域
app.delete('/api/service-areas/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '服务区域删除成功',
    data: {
      id: parseInt(id)
    }
  })
})

// 切换服务区域状态
app.put('/api/service-areas/:id/status', (req, res) => {
  const { id } = req.params
  const { status } = req.body

  res.json({
    code: 200,
    message: '服务区域状态更新成功',
    data: {
      id: parseInt(id),
      status: status,
      updateTime: new Date().toISOString()
    }
  })
})

// 财务管理相关接口
// 获取财务余额信息
app.get('/api/finance/balance/info', (req, res) => {
  res.json({
    code: 200,
    message: '获取财务余额信息成功',
    data: {
      availableBalance: 0,
      frozenBalance: 0,
      pendingBalance: 0,
      totalIncome: 0,
      totalExpense: 0,
      monthlyIncome: 0,
      monthlyExpense: 0,
      lastUpdateTime: new Date().toISOString()
    }
  })
})

// 获取收入统计
app.get('/api/finance/income/stats', (req, res) => {
  const { timeRange = 'month' } = req.query

  res.json({
    code: 200,
    message: '获取收入统计成功',
    data: {
      timeRange: timeRange,
      totalIncome: 0,
      orderIncome: 0,
      otherIncome: 0,
      trend: 0,
      chartData: [],
      lastUpdateTime: new Date().toISOString()
    }
  })
})

// 获取交易记录
app.get('/api/finance/transactions', (req, res) => {
  const { page = 0, size = 20, type, status, startDate, endDate } = req.query

  res.json({
    code: 200,
    message: '获取交易记录成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size),
      summary: {
        totalIncome: 0,
        totalExpense: 0,
        netIncome: 0
      }
    }
  })
})

// 获取银行卡列表
app.get('/api/finance/bank-cards', (req, res) => {
  res.json({
    code: 200,
    message: '获取银行卡列表成功',
    data: []
  })
})

// 添加银行卡
app.post('/api/finance/bank-cards', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '银行卡添加成功',
    data: {
      id: Date.now(),
      ...data,
      status: 'active',
      createTime: new Date().toISOString()
    }
  })
})

// 删除银行卡
app.delete('/api/finance/bank-cards/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '银行卡删除成功',
    data: {
      id: parseInt(id)
    }
  })
})

// 设置默认银行卡
app.put('/api/finance/bank-cards/:id/default', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '默认银行卡设置成功',
    data: {
      id: parseInt(id),
      isDefault: true,
      updateTime: new Date().toISOString()
    }
  })
})

// 导出交易记录
app.get('/api/finance/transactions/export', (req, res) => {
  // 模拟Excel文件
  const excelBuffer = Buffer.from('交易记录导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', 'attachment; filename=transactions.xlsx')
  res.send(excelBuffer)
})

// 获取财务统计概览
app.get('/api/finance/overview', (req, res) => {
  res.json({
    code: 200,
    message: '获取财务概览成功',
    data: {
      todayIncome: 0,
      monthlyIncome: 0,
      totalIncome: 0,
      availableBalance: 0,
      pendingOrders: 0,
      completedOrders: 0,
      refundAmount: 0,
      commissionRate: 0
    }
  })
})

// 获取财务风险状态
app.get('/api/finance/risk/status', (req, res) => {
  res.json({
    code: 200,
    message: '获取财务风险状态成功',
    data: {
      riskLevel: 'low', // low, medium, high
      riskScore: 0,
      riskFactors: [],
      alerts: [],
      recommendations: [],
      lastAssessment: new Date().toISOString(),
      nextAssessment: new Date(Date.now() + 24 * 60 * 60 * 1000).toISOString()
    }
  })
})

// 获取财务分析数据
app.get('/api/finance/analysis', (req, res) => {
  const { timeRange = 'month' } = req.query

  res.json({
    code: 200,
    message: '获取财务分析成功',
    data: {
      timeRange: timeRange,
      overview: {
        totalRevenue: 0,
        totalExpense: 0,
        netProfit: 0,
        profitMargin: 0,
        growthRate: 0
      },
      revenueAnalysis: {
        byService: [],
        byRegion: [],
        byTime: [],
        trends: []
      },
      expenseAnalysis: {
        byCategory: [],
        byTime: [],
        trends: []
      },
      profitAnalysis: {
        grossProfit: 0,
        operatingProfit: 0,
        netProfit: 0,
        profitTrends: []
      },
      cashFlow: {
        operatingCashFlow: 0,
        investingCashFlow: 0,
        financingCashFlow: 0,
        netCashFlow: 0,
        cashFlowTrends: []
      },
      kpis: {
        averageOrderValue: 0,
        customerLifetimeValue: 0,
        customerAcquisitionCost: 0,
        returnOnInvestment: 0
      },
      forecasts: {
        nextMonthRevenue: 0,
        nextQuarterRevenue: 0,
        yearEndProjection: 0
      },
      recommendations: [
        '建议优化成本结构',
        '关注现金流管理',
        '提升客户价值'
      ]
    }
  })
})

// 获取在途资金详情
app.get('/api/finance/pending/details', (req, res) => {
  res.json({
    code: 200,
    message: '获取在途资金详情成功',
    data: {
      totalPending: 0,
      pendingOrders: [],
      pendingWithdrawals: [],
      pendingRefunds: [],
      pendingDeposits: [],
      summary: {
        ordersPending: 0,
        withdrawalsPending: 0,
        refundsPending: 0,
        depositsPending: 0,
        estimatedSettlementDate: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
        riskLevel: 'low'
      },
      breakdown: {
        byStatus: [
          {
            status: 'processing',
            name: '处理中',
            amount: 0,
            count: 0
          },
          {
            status: 'pending_settlement',
            name: '待结算',
            amount: 0,
            count: 0
          },
          {
            status: 'risk_review',
            name: '风控审核',
            amount: 0,
            count: 0
          }
        ],
        byTimeRange: [
          {
            range: '1-3天',
            amount: 0,
            count: 0
          },
          {
            range: '4-7天',
            amount: 0,
            count: 0
          },
          {
            range: '8-14天',
            amount: 0,
            count: 0
          },
          {
            range: '超过14天',
            amount: 0,
            count: 0
          }
        ]
      },
      tips: [
        '在途资金将在14个工作日内结算到账',
        '如有疑问请联系客服',
        '保持良好的服务质量有助于加快结算'
      ]
    }
  })
})

// 订单管理相关接口
// 获取订单统计（必须在 :id 路由之前）
app.get('/api/orders/stats', (req, res) => {
  res.json({
    code: 200,
    message: '获取订单统计成功',
    data: {
      total: 0,
      pending: 0,
      processing: 0,
      completed: 0,
      cancelled: 0,
      todayOrders: 0,
      monthlyOrders: 0
    }
  })
})

// 导出订单数据（必须在 :id 路由之前）
app.get('/api/orders/export', (req, res) => {
  // 模拟Excel文件
  const excelBuffer = Buffer.from('订单数据导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', 'attachment; filename=orders.xlsx')
  res.send(excelBuffer)
})

// 保证金管理相关接口
// 获取保证金概览
app.get('/api/deposit/overview', (req, res) => {
  res.json({
    code: 200,
    message: '获取保证金概览成功',
    data: {
      totalDeposit: 0,
      availableDeposit: 0,
      frozenDeposit: 0,
      usedDeposit: 0,
      depositStatus: 'insufficient',
      lastUpdateTime: new Date().toISOString()
    }
  })
})

// 获取保证金记录
app.get('/api/deposit/records', (req, res) => {
  const { page = 0, size = 10, type, status } = req.query

  res.json({
    code: 200,
    message: '获取保证金记录成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 获取保证金配置
app.get('/api/deposit/config', (req, res) => {
  res.json({
    code: 200,
    message: '获取保证金配置成功',
    data: {
      serviceTypes: [
        { type: 'LAUNDRY', name: '洗衣服务', amount: 1000, required: true },
        { type: 'SHOES', name: '洗鞋服务', amount: 500, required: false },
        { type: 'PET', name: '宠物洗护', amount: 800, required: false },
        { type: 'BAG', name: '包包清洗', amount: 300, required: false },
        { type: 'BEDDING', name: '床品洗护', amount: 600, required: false },
        { type: 'CAR', name: '汽车清洗', amount: 1200, required: false },
        { type: 'HOME_CLEANING', name: '家政清洁', amount: 1500, required: false },
        { type: 'PLUMBING', name: '管道疏通', amount: 800, required: false }
      ],
      minAmount: 100,
      maxAmount: 10000,
      refundPolicy: '店铺关闭后，如无纠纷，保证金将在3个月后自动退还'
    }
  })
})

// 获取扣款优先级
app.get('/api/deposit/deduction-priority', (req, res) => {
  res.json({
    code: 200,
    message: '获取扣款优先级成功',
    data: {
      priority: 'balance_first', // balance_first: 优先扣除可用余额, deposit_first: 优先扣除保证金
      description: '当发生违约扣款时，优先从可用余额中扣除，余额不足时再从保证金中扣除'
    }
  })
})

// 设置扣款优先级
app.put('/api/deposit/deduction-priority', (req, res) => {
  const { priority } = req.body

  res.json({
    code: 200,
    message: '扣款优先级设置成功',
    data: {
      priority: priority,
      updateTime: new Date().toISOString()
    }
  })
})

// 缴纳保证金
app.post('/api/deposit/pay', (req, res) => {
  const { serviceType, amount, paymentMethod } = req.body
  const merchantId = 'merchant_001' // 实际应从token中获取
  const orderId = `DP${Date.now()}`

  // 检查银行卡绑定状态
  const bankCard = bankCardMap.get(merchantId)
  if (!bankCard) {
    res.json({
      code: 403,
      message: '请先绑定银行卡才能进行保证金缴纳',
      data: {
        requireBankCard: true,
        redirectTo: '/main/settings/bankcard'
      }
    })
    return
  }

  // 检查身份证验证状态
  const idCardVerification = idCardVerificationMap.get(merchantId)
  if (!idCardVerification) {
    res.json({
      code: 403,
      message: '请先完成身份证实名认证',
      data: {
        requireIdCard: true,
        redirectTo: '/main/settings/bankcard'
      }
    })
    return
  }

  // 根据支付方式返回不同的支付信息
  let paymentInfo = {}

  if (paymentMethod === 'alipay') {
    paymentInfo = {
      type: 'alipay',
      qrCode: `https://qr.alipay.com/bax08861lmca2rw4ftjw00b8`,
      payUrl: `https://openapi.alipay.com/gateway.do?method=alipay.trade.page.pay&app_id=2021000000000000&charset=UTF-8&sign_type=RSA2&timestamp=${new Date().toISOString()}&version=1.0&notify_url=https://api.merchant.com/notify&return_url=https://merchant.com/return&biz_content={"out_trade_no":"${orderId}","product_code":"FAST_INSTANT_TRADE_PAY","total_amount":"${amount}","subject":"保证金缴纳-${serviceType}"}`,
      expireTime: new Date(Date.now() + 15 * 60 * 1000).toISOString()
    }
  } else if (paymentMethod === 'wechat') {
    paymentInfo = {
      type: 'wechat',
      qrCode: `weixin://wxpay/bizpayurl?pr=${orderId}`,
      prepayId: `wx${Date.now()}`,
      expireTime: new Date(Date.now() + 15 * 60 * 1000).toISOString()
    }
  } else if (paymentMethod === 'bank') {
    paymentInfo = {
      type: 'bank',
      payUrl: `https://pay.bank.com/gateway?orderId=${orderId}&amount=${amount}&returnUrl=https://merchant.com/return&notifyUrl=https://api.merchant.com/notify`,
      expireTime: new Date(Date.now() + 30 * 60 * 1000).toISOString()
    }
  }

  // 存储订单状态
  const orderData = {
    orderId: orderId,
    serviceType: serviceType,
    amount: amount,
    paymentMethod: paymentMethod,
    status: 'pending',
    createTime: new Date().toISOString(),
    expireTime: paymentInfo.expireTime,
    message: '待支付'
  }

  orderStatusMap.set(orderId, orderData)

  res.json({
    code: 200,
    message: '保证金订单创建成功，请完成支付',
    data: {
      orderId: orderId,
      serviceType: serviceType,
      amount: amount,
      paymentMethod: paymentMethod,
      status: 'pending',
      createTime: new Date().toISOString(),
      expireTime: paymentInfo.expireTime,
      paymentInfo: paymentInfo,
      checkUrl: `/api/deposit/pay/status/${orderId}`
    }
  })
})

// 查询保证金支付状态
app.get('/api/deposit/pay/status/:orderId', (req, res) => {
  const { orderId } = req.params

  // 从存储中获取订单状态
  let orderStatus = orderStatusMap.get(orderId)

  if (!orderStatus) {
    // 如果订单不存在，返回错误
    res.json({
      code: 404,
      message: '订单不存在',
      data: null
    })
    return
  }

  // 检查订单是否已过期
  const now = new Date().getTime()
  const expireTime = new Date(orderStatus.expireTime).getTime()

  if (now > expireTime && orderStatus.status === 'pending') {
    // 订单已过期，更新状态并记录到保证金记录
    orderStatus.status = 'expired'
    orderStatus.message = '支付已超时'
    orderStatus.expiredTime = new Date().toISOString()
    orderStatusMap.set(orderId, orderStatus)

    // 记录过期的保证金订单到保证金记录
    const merchantId = 'merchant_001' // 实际应从token中获取
    let merchantRecords = depositRecordsMap.get(merchantId) || []

    const expiredRecord = {
      id: Date.now(),
      orderId: orderId,
      serviceType: orderStatus.serviceType || 'unknown',
      amount: orderStatus.amount || 0,
      paymentMethod: orderStatus.paymentMethod || 'unknown',
      status: 'expired',
      createTime: orderStatus.createTime,
      expiredTime: orderStatus.expiredTime,
      type: 'deposit'
    }

    merchantRecords.push(expiredRecord)
    depositRecordsMap.set(merchantId, merchantRecords)

    console.log(`保证金订单 ${orderId} 已过期，已记录到保证金记录`)
  }

  res.json({
    code: 200,
    message: '查询成功',
    data: {
      orderId: orderId,
      status: orderStatus.status,
      message: orderStatus.message,
      paidTime: orderStatus.paidTime || null,
      failReason: orderStatus.failReason || null
    }
  })
})

// 申请退还保证金
app.post('/api/deposit/refund', (req, res) => {
  const { serviceType, reason } = req.body

  res.json({
    code: 200,
    message: '退还申请提交成功',
    data: {
      id: Date.now(),
      serviceType: serviceType,
      reason: reason,
      status: 'pending',
      applyTime: new Date().toISOString()
    }
  })
})

// 获取保证金统计
app.get('/api/deposit/stats', (req, res) => {
  res.json({
    code: 200,
    message: '获取保证金统计成功',
    data: {
      totalPaid: 0,
      totalRefunded: 0,
      totalFrozen: 0,
      totalUsed: 0,
      serviceTypeStats: []
    }
  })
})

// 获取已缴纳服务类型
app.get('/api/deposit/paid-service-types', (req, res) => {
  res.json({
    code: 200,
    message: '获取已缴纳服务类型成功',
    data: [
      {
        id: 1,
        type: 'laundry',
        name: '衣物洗护',
        icon: '👔',
        depositAmount: 1000,
        paidAmount: 1000,
        status: 'paid',
        paidTime: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString(),
        expiryTime: new Date(Date.now() + 335 * 24 * 60 * 60 * 1000).toISOString(),
        canPublishServices: true,
        servicesPublished: 0,
        maxServices: 10,
        description: '提供各类衣物清洗、熨烫、保养服务'
      },
      {
        id: 2,
        type: 'shoes',
        name: '鞋类清洗',
        icon: '👟',
        depositAmount: 500,
        paidAmount: 500,
        status: 'paid',
        paidTime: new Date(Date.now() - 15 * 24 * 60 * 60 * 1000).toISOString(),
        expiryTime: new Date(Date.now() + 350 * 24 * 60 * 60 * 1000).toISOString(),
        canPublishServices: true,
        servicesPublished: 0,
        maxServices: 5,
        description: '专业鞋类清洗、护理、修复服务'
      }
    ]
  })
})

// 获取未缴纳服务类型
app.get('/api/deposit/unpaid-service-types', (req, res) => {
  res.json({
    code: 200,
    message: '获取未缴纳服务类型成功',
    data: [
      {
        id: 3,
        type: 'pets',
        name: '宠物用品',
        icon: '🐕',
        depositAmount: 800,
        paidAmount: 0,
        status: 'unpaid',
        canPublishServices: false,
        servicesPublished: 0,
        maxServices: 8,
        description: '宠物服装、用品清洗消毒服务'
      },
      {
        id: 4,
        type: 'bags',
        name: '包包护理',
        icon: '👜',
        depositAmount: 600,
        paidAmount: 0,
        status: 'unpaid',
        canPublishServices: false,
        servicesPublished: 0,
        maxServices: 6,
        description: '各类包包清洗、保养、修复服务'
      },
      {
        id: 5,
        type: 'bedding',
        name: '床上用品',
        icon: '🛏️',
        depositAmount: 700,
        paidAmount: 0,
        status: 'unpaid',
        canPublishServices: false,
        servicesPublished: 0,
        maxServices: 7,
        description: '床单、被套、枕头等床上用品清洗'
      },
      {
        id: 6,
        type: 'car_wash',
        name: '汽车清洗',
        icon: '🚗',
        depositAmount: 1500,
        paidAmount: 0,
        status: 'unpaid',
        canPublishServices: false,
        servicesPublished: 0,
        maxServices: 15,
        description: '汽车内外清洗、美容、保养服务'
      },
      {
        id: 7,
        type: 'home_cleaning',
        name: '家政清洁',
        icon: '🏠',
        depositAmount: 2000,
        paidAmount: 0,
        status: 'unpaid',
        canPublishServices: false,
        servicesPublished: 0,
        maxServices: 20,
        description: '家庭深度清洁、保洁服务'
      },
      {
        id: 8,
        type: 'plumbing',
        name: '管道疏通',
        icon: '🔧',
        depositAmount: 1200,
        paidAmount: 0,
        status: 'unpaid',
        canPublishServices: false,
        servicesPublished: 0,
        maxServices: 12,
        description: '管道疏通、维修、清洁服务'
      }
    ]
  })
})

// 获取服务保证金要求
app.get('/api/deposit/service-requirements', (req, res) => {
  // 使用配置中的服务保证金要求数据
  const serviceRequirements = Object.values(SERVICE_DEPOSIT_CONFIG).map((config, index) => ({
    id: index + 1,
    type: config.type,
    name: config.name,
    icon: getServiceIcon(config.type),
    depositAmount: config.deposit,
    riskLevel: getRiskLevel(config.deposit),
    description: config.description,
    requirements: getServiceRequirements(config.type),
    maxServices: getMaxServices(config.type),
    settlementCycle: 14,
    refundPolicy: '无争议情况下可申请退还'
  }))

  res.json({
    code: 200,
    message: '获取服务保证金要求成功',
    data: serviceRequirements
  })
})

// 消息中心相关接口
// 获取消息列表
app.get('/api/messages', (req, res) => {
  const { page = 0, size = 10, type, status } = req.query

  res.json({
    code: 200,
    message: '获取消息列表成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size),
      unreadCount: 0
    }
  })
})

// 获取消息详情
app.get('/api/messages/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '获取消息详情成功',
    data: {
      id: parseInt(id),
      title: '消息标题',
      content: '消息内容',
      type: 'system',
      status: 'unread',
      createTime: new Date().toISOString()
    }
  })
})

// 标记消息为已读
app.put('/api/messages/:id/read', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '消息已标记为已读',
    data: {
      id: parseInt(id),
      status: 'read',
      readTime: new Date().toISOString()
    }
  })
})

// 回复消息
app.post('/api/messages/:id/reply', (req, res) => {
  const { id } = req.params
  const { content } = req.body

  res.json({
    code: 200,
    message: '消息回复成功',
    data: {
      id: parseInt(id),
      replyContent: content,
      replyTime: new Date().toISOString()
    }
  })
})

// 获取消息统计
app.get('/api/messages/statistics', (req, res) => {
  res.json({
    code: 200,
    message: '获取消息统计成功',
    data: {
      total: 0,
      unread: 0,
      read: 0,
      replied: 0,
      typeStats: {
        system: 0,
        order: 0,
        finance: 0,
        review: 0,
        promotion: 0,
        customer: 0
      }
    }
  })
})

// 优惠券管理相关接口
// 获取优惠券列表
app.get('/api/coupons', (req, res) => {
  const { page = 0, size = 10, name, type, status } = req.query

  res.json({
    code: 200,
    message: '获取优惠券列表成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 创建优惠券
app.post('/api/coupons', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '优惠券创建成功',
    data: {
      id: Date.now(),
      ...data,
      status: 'active',
      createTime: new Date().toISOString()
    }
  })
})

// 获取优惠券详情
app.get('/api/coupons/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '获取优惠券详情成功',
    data: {
      id: parseInt(id),
      name: '优惠券名称',
      type: 'discount',
      value: 10,
      status: 'active',
      createTime: new Date().toISOString()
    }
  })
})

// 更新优惠券
app.put('/api/coupons/:id', (req, res) => {
  const { id } = req.params
  const data = req.body

  res.json({
    code: 200,
    message: '优惠券更新成功',
    data: {
      id: parseInt(id),
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 删除优惠券
app.delete('/api/coupons/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '优惠券删除成功',
    data: {
      id: parseInt(id)
    }
  })
})

// 获取优惠券统计
app.get('/api/coupons/statistics', (req, res) => {
  res.json({
    code: 200,
    message: '获取优惠券统计成功',
    data: {
      total: 0,
      active: 0,
      expired: 0,
      used: 0,
      totalUsage: 0,
      totalSavings: 0
    }
  })
})

// 账户管理相关接口
// 获取商户资料
app.get('/api/account/profile', (req, res) => {
  res.json({
    code: 200,
    message: '获取商户资料成功',
    data: {
      id: 1,
      name: '',
      phone: '',
      email: '',
      address: '',
      region: '',
      description: '',
      avatar: '',
      serviceTypes: [],
      status: 'active',
      createTime: new Date().toISOString()
    }
  })
})

// 更新商户资料
app.put('/api/account/profile', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '商户资料更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 修改密码
app.post('/api/account/change-password', (req, res) => {
  const { oldPassword, newPassword } = req.body

  res.json({
    code: 200,
    message: '密码修改成功',
    data: {
      updateTime: new Date().toISOString()
    }
  })
})

// 上传头像
app.post('/api/account/upload-avatar', (req, res) => {
  res.json({
    code: 200,
    message: '头像上传成功',
    data: {
      avatarUrl: '/uploads/avatar/default.jpg',
      uploadTime: new Date().toISOString()
    }
  })
})

// 获取安全设置
app.get('/api/account/security', (req, res) => {
  res.json({
    code: 200,
    message: '获取安全设置成功',
    data: {
      twoFactorEnabled: false,
      loginNotification: true,
      securityQuestions: [],
      lastLoginTime: new Date().toISOString(),
      loginHistory: []
    }
  })
})

// 帮助中心相关接口
// 获取帮助文档列表
app.get('/api/help/docs', (req, res) => {
  const { category, keyword } = req.query

  res.json({
    code: 200,
    message: '获取帮助文档成功',
    data: {
      categories: [
        { id: 1, name: '快速入门', count: 0 },
        { id: 2, name: '订单管理', count: 0 },
        { id: 3, name: '财务管理', count: 0 },
        { id: 4, name: '服务管理', count: 0 },
        { id: 5, name: '常见问题', count: 0 }
      ],
      documents: []
    }
  })
})

// 获取帮助文档详情
app.get('/api/help/docs/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '获取文档详情成功',
    data: {
      id: parseInt(id),
      title: '帮助文档标题',
      content: '帮助文档内容',
      category: '快速入门',
      tags: [],
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }
  })
})

// 获取常见问题
app.get('/api/help/faq', (req, res) => {
  res.json({
    code: 200,
    message: '获取常见问题成功',
    data: []
  })
})

// 提交反馈
app.post('/api/help/feedback', (req, res) => {
  const { type, content, contact } = req.body

  res.json({
    code: 200,
    message: '反馈提交成功',
    data: {
      id: Date.now(),
      type: type,
      content: content,
      contact: contact,
      status: 'pending',
      submitTime: new Date().toISOString()
    }
  })
})

// 获取联系方式
app.get('/api/help/contact', (req, res) => {
  res.json({
    code: 200,
    message: '获取联系方式成功',
    data: {
      phone: '400-123-4567',
      email: 'support@laundry.com',
      qq: '123456789',
      wechat: 'laundry_support',
      workTime: '周一至周日 9:00-18:00',
      address: '北京市朝阳区xxx街道xxx号'
    }
  })
})

// 营业管理相关接口
// 获取营业概览
app.get('/api/business/overview', (req, res) => {
  res.json({
    code: 200,
    message: '获取营业概览成功',
    data: {
      businessStatus: 'open',
      todayOrders: 0,
      todayRevenue: 0,
      onlineServices: 0,
      totalServices: 0,
      customerSatisfaction: 0,
      responseRate: 0,
      lastUpdateTime: new Date().toISOString()
    }
  })
})

// 获取营业时间
app.get('/api/business/hours', (req, res) => {
  res.json({
    code: 200,
    message: '获取营业时间成功',
    data: {
      isOpen24Hours: false,
      businessHours: [
        { day: 'monday', startTime: '09:00', endTime: '18:00', isOpen: true },
        { day: 'tuesday', startTime: '09:00', endTime: '18:00', isOpen: true },
        { day: 'wednesday', startTime: '09:00', endTime: '18:00', isOpen: true },
        { day: 'thursday', startTime: '09:00', endTime: '18:00', isOpen: true },
        { day: 'friday', startTime: '09:00', endTime: '18:00', isOpen: true },
        { day: 'saturday', startTime: '09:00', endTime: '18:00', isOpen: true },
        { day: 'sunday', startTime: '09:00', endTime: '18:00', isOpen: true }
      ],
      holidays: [],
      specialHours: []
    }
  })
})

// 更新营业时间
app.put('/api/business/hours', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '营业时间更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 获取营业状态
app.get('/api/business/status', (req, res) => {
  res.json({
    code: 200,
    message: '获取营业状态成功',
    data: {
      status: 'open', // open, closed, busy, maintenance
      autoAcceptOrders: true,
      maxDailyOrders: 100,
      currentOrders: 0,
      pauseReason: '',
      estimatedResumeTime: null
    }
  })
})

// 更新营业状态
app.put('/api/business/status', (req, res) => {
  const { status, autoAcceptOrders, maxDailyOrders, pauseReason } = req.body

  res.json({
    code: 200,
    message: '营业状态更新成功',
    data: {
      status: status,
      autoAcceptOrders: autoAcceptOrders,
      maxDailyOrders: maxDailyOrders,
      pauseReason: pauseReason,
      updateTime: new Date().toISOString()
    }
  })
})

// 切换营业状态 (POST方法)
app.post('/api/business/status', (req, res) => {
  const { status, autoAcceptOrders, maxDailyOrders, pauseReason } = req.body

  res.json({
    code: 200,
    message: '营业状态切换成功',
    data: {
      status: status,
      autoAcceptOrders: autoAcceptOrders,
      maxDailyOrders: maxDailyOrders,
      pauseReason: pauseReason,
      updateTime: new Date().toISOString()
    }
  })
})

// 账户充值
app.post('/api/business/recharge', (req, res) => {
  const { amount, paymentMethod, remark } = req.body
  const merchantId = 'merchant_001' // 实际应从token中获取
  const orderId = `RC${Date.now()}`

  // 检查银行卡绑定状态
  const bankCard = bankCardMap.get(merchantId)
  if (!bankCard) {
    res.json({
      code: 403,
      message: '请先绑定银行卡才能进行充值操作',
      data: {
        requireBankCard: true,
        redirectTo: '/main/settings/bankcard'
      }
    })
    return
  }

  // 检查身份证验证状态
  const idCardVerification = idCardVerificationMap.get(merchantId)
  if (!idCardVerification) {
    res.json({
      code: 403,
      message: '请先完成身份证实名认证',
      data: {
        requireIdCard: true,
        redirectTo: '/main/settings/bankcard'
      }
    })
    return
  }

  // 根据支付方式返回不同的支付信息
  let paymentInfo = {}

  if (paymentMethod === 'alipay') {
    // 支付宝支付
    paymentInfo = {
      type: 'alipay',
      qrCode: `https://qr.alipay.com/bax08861lmca2rw4ftjw00a7`, // 模拟支付宝二维码
      payUrl: `https://openapi.alipay.com/gateway.do?method=alipay.trade.page.pay&app_id=2021000000000000&charset=UTF-8&sign_type=RSA2&timestamp=${new Date().toISOString()}&version=1.0&notify_url=https://api.merchant.com/notify&return_url=https://merchant.com/return&biz_content={"out_trade_no":"${orderId}","product_code":"FAST_INSTANT_TRADE_PAY","total_amount":"${amount}","subject":"商户账户充值"}`,
      expireTime: new Date(Date.now() + 15 * 60 * 1000).toISOString(), // 15分钟过期
      instructions: [
        '请使用支付宝扫描二维码完成支付',
        '或点击支付链接跳转到支付宝页面',
        '支付完成后页面将自动跳转'
      ]
    }
  } else if (paymentMethod === 'wechat') {
    // 微信支付
    paymentInfo = {
      type: 'wechat',
      qrCode: `weixin://wxpay/bizpayurl?pr=${orderId}`, // 模拟微信支付二维码
      prepayId: `wx${Date.now()}`,
      expireTime: new Date(Date.now() + 15 * 60 * 1000).toISOString(), // 15分钟过期
      instructions: [
        '请使用微信扫描二维码完成支付',
        '或在微信中打开支付链接',
        '支付完成后页面将自动更新'
      ]
    }
  } else if (paymentMethod === 'bank') {
    // 银行卡支付
    paymentInfo = {
      type: 'bank',
      payUrl: `https://pay.bank.com/gateway?orderId=${orderId}&amount=${amount}&returnUrl=https://merchant.com/return&notifyUrl=https://api.merchant.com/notify`,
      bankList: [
        { code: 'ICBC', name: '工商银行', icon: 'icbc.png' },
        { code: 'CCB', name: '建设银行', icon: 'ccb.png' },
        { code: 'ABC', name: '农业银行', icon: 'abc.png' },
        { code: 'BOC', name: '中国银行', icon: 'boc.png' },
        { code: 'CMB', name: '招商银行', icon: 'cmb.png' }
      ],
      expireTime: new Date(Date.now() + 30 * 60 * 1000).toISOString(), // 30分钟过期
      instructions: [
        '点击下方按钮跳转到银行支付页面',
        '选择您的银行卡完成支付',
        '支付完成后将自动返回'
      ]
    }
  }

  // 存储订单状态
  const orderData = {
    orderId: orderId,
    amount: amount,
    paymentMethod: paymentMethod,
    remark: remark,
    status: 'pending', // pending: 待支付, paid: 已支付, failed: 支付失败, expired: 已过期
    createTime: new Date().toISOString(),
    expireTime: paymentInfo.expireTime,
    message: '待支付'
  }

  orderStatusMap.set(orderId, orderData)

  res.json({
    code: 200,
    message: '充值订单创建成功，请完成支付',
    data: {
      orderId: orderId,
      amount: amount,
      paymentMethod: paymentMethod,
      remark: remark,
      status: 'pending',
      createTime: new Date().toISOString(),
      expireTime: paymentInfo.expireTime,
      paymentInfo: paymentInfo,
      checkUrl: `/api/business/recharge/status/${orderId}` // 支付状态查询接口
    }
  })
})

// 存储订单状态（在真实环境中应该使用数据库）
const orderStatusMap = new Map()

// 存储银行卡绑定信息（在真实环境中应该使用数据库）
const bankCardMap = new Map()

// 存储身份证验证信息
const idCardVerificationMap = new Map()

// 存储充值记录（在真实环境中应该使用数据库）
const rechargeRecordsMap = new Map()

// 存储保证金记录（在真实环境中应该使用数据库）
const depositRecordsMap = new Map()

// 存储退店申请记录
const storeClosureApplicationsMap = new Map()

// 存储订单数据（模拟）
const ordersMap = new Map()

// 存储纠纷记录
const disputesMap = new Map()

// 存储罚款记录
const penaltiesMap = new Map()

// 存储其他服务记录
const otherServicesMap = new Map()

// 服务类型保证金配置
const SERVICE_DEPOSIT_CONFIG = {
  laundry: {
    type: 'laundry',
    name: '衣物洗护',
    description: '提供各类衣物清洗、熨烫、保养服务',
    deposit: 500,
    icon: 'laundry'
  },
  shoes: {
    type: 'shoes',
    name: '鞋类清洗',
    description: '专业鞋类清洗、护理、修复服务',
    deposit: 300,
    icon: 'shoes'
  },
  pet: {
    type: 'pet',
    name: '宠物用品',
    description: '宠物服装、用品清洗消毒服务',
    deposit: 1000,
    icon: 'pet'
  },
  bag: {
    type: 'bag',
    name: '包包护理',
    description: '各类包包清洗、保养、修复服务',
    deposit: 400,
    icon: 'bag'
  },
  bedding: {
    type: 'bedding',
    name: '床上用品',
    description: '床单、被套、枕头等床上用品清洗',
    deposit: 600,
    icon: 'bedding'
  },
  car: {
    type: 'car',
    name: '汽车清洗',
    description: '汽车内外清洗、美容、保养服务',
    deposit: 3000,
    icon: 'car'
  },
  home_cleaning: {
    type: 'home_cleaning',
    name: '家政清洁',
    description: '家庭深度清洁、保洁服务',
    deposit: 2000,
    icon: 'home'
  },
  plumbing: {
    type: 'plumbing',
    name: '管道疏通',
    description: '管道疏通、维修、清洁服务',
    deposit: 500,
    icon: 'plumbing'
  }
}

// 查询充值状态
app.get('/api/business/recharge/status/:orderId', (req, res) => {
  const { orderId } = req.params

  // 从存储中获取订单状态
  let orderStatus = orderStatusMap.get(orderId)

  if (!orderStatus) {
    // 如果订单不存在，返回错误
    res.json({
      code: 404,
      message: '订单不存在',
      data: null
    })
    return
  }

  // 检查订单是否已过期
  const now = new Date().getTime()
  const expireTime = new Date(orderStatus.expireTime).getTime()

  if (now > expireTime && orderStatus.status === 'pending') {
    // 订单已过期，更新状态并记录到充值记录
    orderStatus.status = 'expired'
    orderStatus.message = '支付已超时'
    orderStatus.expiredTime = new Date().toISOString()
    orderStatusMap.set(orderId, orderStatus)

    // 记录过期的充值订单到充值记录
    const merchantId = 'merchant_001' // 实际应从token中获取
    let merchantRecords = rechargeRecordsMap.get(merchantId) || []

    const expiredRecord = {
      id: Date.now(),
      orderId: orderId,
      amount: orderStatus.amount || 0,
      paymentMethod: orderStatus.paymentMethod || 'unknown',
      status: 'expired',
      remark: orderStatus.remark || '',
      createTime: orderStatus.createTime,
      expiredTime: orderStatus.expiredTime,
      type: 'recharge'
    }

    merchantRecords.push(expiredRecord)
    rechargeRecordsMap.set(merchantId, merchantRecords)

    console.log(`充值订单 ${orderId} 已过期，已记录到充值记录`)
  }

  res.json({
    code: 200,
    message: '查询成功',
    data: {
      orderId: orderId,
      status: orderStatus.status,
      message: orderStatus.message,
      paidTime: orderStatus.paidTime || null,
      failReason: orderStatus.failReason || null
    }
  })
})

// 模拟支付成功接口（仅用于测试，真实环境中由第三方支付平台回调）
app.post('/api/business/recharge/simulate-payment/:orderId', (req, res) => {
  const { orderId } = req.params
  const { success } = req.body

  let orderStatus = orderStatusMap.get(orderId)

  if (!orderStatus) {
    res.json({
      code: 404,
      message: '订单不存在',
      data: null
    })
    return
  }

  if (orderStatus.status !== 'pending') {
    res.json({
      code: 400,
      message: '订单状态不允许修改',
      data: null
    })
    return
  }

  // 更新订单状态
  if (success) {
    orderStatus.status = 'paid'
    orderStatus.message = '支付成功'
    orderStatus.paidTime = new Date().toISOString()
  } else {
    orderStatus.status = 'failed'
    orderStatus.message = '支付失败'
    orderStatus.failReason = '模拟支付失败'
  }

  orderStatusMap.set(orderId, orderStatus)

  res.json({
    code: 200,
    message: '支付状态更新成功',
    data: orderStatus
  })
})

// 支付回调接口（模拟）
app.post('/api/business/recharge/notify', (req, res) => {
  const { orderId, status, transactionId } = req.body

  // 在真实环境中，这里会验证回调签名，更新数据库等
  console.log('收到支付回调:', { orderId, status, transactionId })

  res.json({
    code: 200,
    message: 'success'
  })
})

// 获取风控提醒
app.get('/api/business/risk-alerts', (req, res) => {
  res.json({
    code: 200,
    message: '获取风控提醒成功',
    data: {
      alerts: [],
      riskLevel: 'low', // low, medium, high
      totalAlerts: 0,
      unreadAlerts: 0,
      lastCheckTime: new Date().toISOString()
    }
  })
})

// 获取风控提醒详细信息 (前端调用的路径)
app.get('/api/business/risk/alerts', (req, res) => {
  res.json({
    code: 200,
    message: '获取风控提醒成功',
    data: [
      {
        id: 1,
        type: 'refund_rate',
        level: 'medium',
        title: '退款率偏高提醒',
        message: '您的退款率为8.5%，建议关注服务质量',
        isRead: false,
        createdAt: new Date().toISOString(),
        actions: [
          {
            type: 'view_details',
            text: '查看详情'
          },
          {
            type: 'improve_service',
            text: '改进建议'
          }
        ]
      },
      {
        id: 2,
        type: 'response_time',
        level: 'low',
        title: '响应时间提醒',
        message: '您的平均响应时间为3分钟，表现良好',
        isRead: true,
        createdAt: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
        actions: [
          {
            type: 'view_details',
            text: '查看详情'
          }
        ]
      }
    ]
  })
})

// 标记风控提醒已读
app.post('/api/business/risk/alerts/:id/read', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '标记已读成功',
    data: {
      alertId: id,
      readAt: new Date().toISOString()
    }
  })
})

// 获取服务质量指标
app.get('/api/business/quality-metrics', (req, res) => {
  res.json({
    code: 200,
    message: '获取服务质量指标成功',
    data: {
      averageRating: 0,
      responseTime: 0,
      completionRate: 0,
      customerReturnRate: 0,
      complaintRate: 0,
      onTimeDeliveryRate: 0,
      qualityScore: 0,
      lastUpdateTime: new Date().toISOString()
    }
  })
})

// 获取营业统计
app.get('/api/business/statistics', (req, res) => {
  const { timeRange = 'week' } = req.query

  res.json({
    code: 200,
    message: '获取营业统计成功',
    data: {
      timeRange: timeRange,
      orderStats: {
        total: 0,
        completed: 0,
        cancelled: 0,
        pending: 0
      },
      revenueStats: {
        total: 0,
        average: 0,
        trend: 0
      },
      serviceStats: {
        mostPopular: '',
        leastPopular: '',
        averagePrice: 0
      },
      customerStats: {
        new: 0,
        returning: 0,
        satisfaction: 0
      }
    }
  })
})

// 获取服务表现数据
app.get('/api/business/performance', (req, res) => {
  res.json({
    code: 200,
    message: '获取服务表现数据成功',
    data: {
      rating: 0,
      responseTime: 0,
      refundRate: 0,
      badReviewRate: 0,
      completionRate: 0,
      onTimeRate: 0,
      customerSatisfaction: 0,
      qualityScore: 0,
      trends: {
        rating: [],
        responseTime: [],
        refundRate: [],
        badReviewRate: []
      },
      benchmarks: {
        industry: {
          rating: 4.5,
          responseTime: 5,
          refundRate: 3,
          badReviewRate: 2
        },
        platform: {
          rating: 4.3,
          responseTime: 6,
          refundRate: 4,
          badReviewRate: 3
        }
      },
      recommendations: [
        '保持良好的服务质量',
        '及时响应客户咨询',
        '关注客户反馈'
      ]
    }
  })
})

// 获取账户余额
app.get('/api/business/balance', (req, res) => {
  res.json({
    code: 200,
    message: '获取账户余额成功',
    data: {
      balance: 0,
      availableBalance: 0,
      frozenBalance: 0,
      pendingBalance: 0,
      totalIncome: 0,
      totalExpense: 0,
      lastUpdateTime: new Date().toISOString(),
      balanceDetails: {
        orderRevenue: 0,
        promotionCost: 0,
        withdrawalAmount: 0,
        refundAmount: 0,
        depositAmount: 0,
        penaltyAmount: 0
      },
      recentTransactions: []
    }
  })
})

// 获取营业设置
app.get('/api/business/settings', (req, res) => {
  res.json({
    code: 200,
    message: '获取营业设置成功',
    data: {
      autoAcceptOrders: true,
      maxDailyOrders: 100,
      orderTimeout: 30,
      deliveryRadius: 5,
      minOrderAmount: 20,
      freeDeliveryAmount: 50,
      emergencyContact: '',
      notificationSettings: {
        newOrder: true,
        orderCancellation: true,
        customerMessage: true,
        systemAlert: true
      }
    }
  })
})

// 更新营业设置
app.put('/api/business/settings', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '营业设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 商家设置相关接口
// 获取商家设置
app.get('/api/settings/merchant', (req, res) => {
  res.json({
    code: 200,
    message: '获取商家设置成功',
    data: {
      basicInfo: {
        name: '',
        phone: '',
        email: '',
        address: '',
        description: '',
        avatar: ''
      },
      businessInfo: {
        businessLicense: '',
        businessScope: '',
        registrationDate: '',
        legalPerson: ''
      },
      serviceSettings: {
        autoAcceptOrders: true,
        maxDailyOrders: 100,
        serviceRadius: 5,
        minOrderAmount: 20,
        freeDeliveryAmount: 50
      },
      notificationSettings: {
        newOrder: true,
        orderUpdate: true,
        customerMessage: true,
        systemNotice: true,
        emailNotification: false,
        smsNotification: true
      }
    }
  })
})

// 更新商家设置
app.put('/api/settings/merchant', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '商家设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 获取营业设置
app.get('/api/settings/business', (req, res) => {
  res.json({
    code: 200,
    message: '获取营业设置成功',
    data: {
      businessHours: {
        isOpen24Hours: false,
        weekdays: {
          monday: { isOpen: true, startTime: '09:00', endTime: '18:00' },
          tuesday: { isOpen: true, startTime: '09:00', endTime: '18:00' },
          wednesday: { isOpen: true, startTime: '09:00', endTime: '18:00' },
          thursday: { isOpen: true, startTime: '09:00', endTime: '18:00' },
          friday: { isOpen: true, startTime: '09:00', endTime: '18:00' },
          saturday: { isOpen: true, startTime: '09:00', endTime: '18:00' },
          sunday: { isOpen: true, startTime: '09:00', endTime: '18:00' }
        }
      },
      orderSettings: {
        autoAcceptOrders: true,
        maxDailyOrders: 100,
        orderTimeout: 30,
        allowCancellation: true,
        cancellationDeadline: 60
      },
      deliverySettings: {
        deliveryRadius: 5,
        minOrderAmount: 20,
        freeDeliveryAmount: 50,
        deliveryFee: 5,
        urgentDeliveryFee: 10
      }
    }
  })
})

// 更新营业设置
app.put('/api/settings/business', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '营业设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 获取风控设置
app.get('/api/settings/risk', (req, res) => {
  res.json({
    code: 200,
    message: '获取风控设置成功',
    data: {
      riskLevel: 'medium',
      autoRiskControl: true,
      maxDailyAmount: 10000,
      maxSingleAmount: 1000,
      suspiciousOrderAlert: true,
      highRiskCustomerAlert: true,
      abnormalBehaviorAlert: true,
      riskControlRules: [
        { type: 'amount', threshold: 1000, action: 'review' },
        { type: 'frequency', threshold: 10, action: 'limit' },
        { type: 'location', threshold: 'outside_area', action: 'alert' }
      ]
    }
  })
})

// 更新风控设置
app.put('/api/settings/risk', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '风控设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 获取通知设置
app.get('/api/settings/notification', (req, res) => {
  res.json({
    code: 200,
    message: '获取通知设置成功',
    data: {
      pushNotification: {
        newOrder: true,
        orderUpdate: true,
        customerMessage: true,
        systemNotice: true,
        promotionUpdate: false
      },
      emailNotification: {
        enabled: false,
        email: '',
        dailyReport: false,
        weeklyReport: false,
        monthlyReport: false
      },
      smsNotification: {
        enabled: true,
        phone: '',
        emergencyOnly: true,
        marketingMessages: false
      },
      soundSettings: {
        enabled: true,
        volume: 80,
        newOrderSound: 'default',
        messageSound: 'default'
      }
    }
  })
})

// 更新通知设置
app.put('/api/settings/notification', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '通知设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 获取界面设置
app.get('/api/settings/interface', (req, res) => {
  res.json({
    code: 200,
    message: '获取界面设置成功',
    data: {
      theme: {
        mode: 'light', // light, dark, auto
        primaryColor: '#409EFF',
        fontSize: 'medium', // small, medium, large
        borderRadius: 'medium' // small, medium, large
      },
      layout: {
        sidebarCollapsed: false,
        showBreadcrumb: true,
        showTabs: true,
        fixedHeader: true,
        fixedSidebar: true
      },
      display: {
        showWelcomeMessage: true,
        showQuickActions: true,
        showStatistics: true,
        showNotifications: true,
        animationEnabled: true,
        compactMode: false
      },
      language: {
        locale: 'zh-CN',
        dateFormat: 'YYYY-MM-DD',
        timeFormat: '24h', // 12h, 24h
        currency: 'CNY'
      },
      accessibility: {
        highContrast: false,
        largeText: false,
        reduceMotion: false,
        screenReader: false
      },
      advanced: {
        enableDebugMode: false,
        showPerformanceMetrics: false,
        enableExperimentalFeatures: false,
        autoSave: true,
        autoSaveInterval: 30 // seconds
      }
    }
  })
})

// 更新界面设置
app.put('/api/settings/interface', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '界面设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 获取服务区域设置
app.get('/api/settings/service-areas', (req, res) => {
  res.json({
    code: 200,
    message: '获取服务区域设置成功',
    data: {
      currentAreas: [
        {
          id: 1,
          province: '北京市',
          city: '北京市',
          district: '朝阳区',
          street: '三里屯街道',
          maxDistance: 5,
          deliveryFee: 0,
          isActive: true,
          priority: 1
        },
        {
          id: 2,
          province: '北京市',
          city: '北京市',
          district: '海淀区',
          street: '中关村街道',
          maxDistance: 8,
          deliveryFee: 5,
          isActive: true,
          priority: 2
        }
      ],
      settings: {
        maxServiceAreas: 10,
        defaultMaxDistance: 5,
        defaultDeliveryFee: 0,
        autoAcceptInArea: true,
        priorityDelivery: true,
        nightServiceEnabled: false,
        nightServiceStartTime: '18:00',
        nightServiceEndTime: '22:00',
        nightServiceFeeMultiplier: 1.5
      },
      availableAreas: [
        {
          province: '北京市',
          cities: [
            {
              name: '北京市',
              districts: [
                {
                  name: '朝阳区',
                  streets: ['三里屯街道', '建外街道', '呼家楼街道', '八里庄街道']
                },
                {
                  name: '海淀区',
                  streets: ['中关村街道', '学院路街道', '清华园街道', '燕园街道']
                },
                {
                  name: '西城区',
                  streets: ['西长安街街道', '新街口街道', '月坛街道', '德胜街道']
                },
                {
                  name: '东城区',
                  streets: ['东华门街道', '景山街道', '交道口街道', '安定门街道']
                }
              ]
            }
          ]
        }
      ]
    }
  })
})

// 更新服务区域设置
app.put('/api/settings/service-areas', (req, res) => {
  const data = req.body

  res.json({
    code: 200,
    message: '服务区域设置更新成功',
    data: {
      ...data,
      updateTime: new Date().toISOString()
    }
  })
})

// 添加服务区域
app.post('/api/settings/service-areas', (req, res) => {
  const { province, city, district, street, maxDistance, deliveryFee } = req.body

  res.json({
    code: 200,
    message: '服务区域添加成功',
    data: {
      id: Date.now(),
      province: province,
      city: city,
      district: district,
      street: street,
      maxDistance: maxDistance,
      deliveryFee: deliveryFee,
      isActive: true,
      priority: 999,
      createTime: new Date().toISOString()
    }
  })
})

// 删除服务区域
app.delete('/api/settings/service-areas/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '服务区域删除成功',
    data: {
      deletedId: id,
      deleteTime: new Date().toISOString()
    }
  })
})

// 推广管理相关接口
// 获取推广方案
app.get('/api/business/promotion/plans', (req, res) => {
  res.json({
    code: 200,
    message: '获取推广方案成功',
    data: {
      plans: [],
      currentPlan: null,
      availablePlans: [
        {
          id: 1,
          name: '基础推广',
          price: 100,
          duration: 7,
          features: ['基础曝光', '搜索优化'],
          description: '适合新商家的基础推广方案'
        },
        {
          id: 2,
          name: '标准推广',
          price: 300,
          duration: 15,
          features: ['优先展示', '搜索置顶', '推荐位'],
          description: '适合稳定经营的商家'
        },
        {
          id: 3,
          name: '高级推广',
          price: 500,
          duration: 30,
          features: ['首页推荐', '全平台曝光', '专属客服'],
          description: '适合快速发展的商家'
        }
      ],
      statistics: {
        totalSpent: 0,
        totalViews: 0,
        totalOrders: 0,
        conversionRate: 0
      }
    }
  })
})

// 购买推广方案
app.post('/api/business/promotion/purchase', (req, res) => {
  const { planId, duration } = req.body

  res.json({
    code: 200,
    message: '推广方案购买成功',
    data: {
      orderId: Date.now(),
      planId: planId,
      duration: duration,
      startTime: new Date().toISOString(),
      endTime: new Date(Date.now() + duration * 24 * 60 * 60 * 1000).toISOString(),
      status: 'active'
    }
  })
})

// 获取推广统计
app.get('/api/business/promotion/statistics', (req, res) => {
  const { timeRange = 'week' } = req.query

  res.json({
    code: 200,
    message: '获取推广统计成功',
    data: {
      timeRange: timeRange,
      totalSpent: 0,
      totalViews: 0,
      totalClicks: 0,
      totalOrders: 0,
      conversionRate: 0,
      roi: 0,
      chartData: [],
      topKeywords: [],
      performanceByPlan: []
    }
  })
})

// 获取推广统计数据 (前端调用的路径)
app.get('/api/business/promotion/stats', (req, res) => {
  res.json({
    code: 200,
    message: '获取推广统计成功',
    data: {
      totalSpent: 0,
      totalViews: 0,
      totalClicks: 0,
      totalOrders: 0,
      conversionRate: 0,
      roi: 0,
      activePromotions: 0,
      avgCpc: 0,
      avgCpm: 0,
      impressions: 0,
      clickThroughRate: 0,
      costPerOrder: 0,
      revenueFromPromotion: 0,
      promotionEfficiency: 0,
      topPerformingAds: [],
      dailyStats: [],
      weeklyTrends: [],
      monthlyComparison: []
    }
  })
})

// 获取推广历史
app.get('/api/business/promotion/history', (req, res) => {
  const { page = 0, size = 10 } = req.query

  res.json({
    code: 200,
    message: '获取推广历史成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 暂停/恢复推广
app.put('/api/business/promotion/toggle', (req, res) => {
  const { action } = req.body // pause, resume

  res.json({
    code: 200,
    message: action === 'pause' ? '推广已暂停' : '推广已恢复',
    data: {
      status: action === 'pause' ? 'paused' : 'active',
      updateTime: new Date().toISOString()
    }
  })
})

// 切换推广自动调节
app.post('/api/business/promotion/auto-adjustment', (req, res) => {
  const { enabled } = req.body

  res.json({
    code: 200,
    message: enabled ? '推广自动调节已开启' : '推广自动调节已关闭',
    data: {
      autoAdjustmentEnabled: enabled,
      updateTime: new Date().toISOString(),
      settings: {
        adjustmentInterval: 60, // 调节间隔（分钟）
        maxBudgetIncrease: 20, // 最大预算增加百分比
        minPerformanceThreshold: 0.05, // 最小性能阈值
        autoOptimizeKeywords: true, // 自动优化关键词
        autoAdjustBidding: true, // 自动调整出价
        smartScheduling: true // 智能排期
      }
    }
  })
})

// 数据统计导出接口
// 导出统计数据
app.get('/api/statistics/export', (req, res) => {
  const { type, timeRange, format, startDate, endDate } = req.query

  // 模拟Excel文件
  const excelBuffer = Buffer.from(`统计数据导出文件
类型: ${type}
时间范围: ${timeRange}
格式: ${format}
开始日期: ${startDate}
结束日期: ${endDate}
导出时间: ${new Date().toISOString()}`)

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', `attachment; filename=statistics_${type}_${timeRange}.xlsx`)
  res.send(excelBuffer)
})

// 导出订单统计
app.get('/api/statistics/orders/export', (req, res) => {
  const { timeRange, format } = req.query

  const excelBuffer = Buffer.from('订单统计导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', `attachment; filename=order_statistics_${timeRange}.xlsx`)
  res.send(excelBuffer)
})

// 导出财务统计
app.get('/api/statistics/finance/export', (req, res) => {
  const { timeRange, format } = req.query

  const excelBuffer = Buffer.from('财务统计导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', `attachment; filename=finance_statistics_${timeRange}.xlsx`)
  res.send(excelBuffer)
})

// 导出客户统计
app.get('/api/statistics/customers/export', (req, res) => {
  const { timeRange, format } = req.query

  const excelBuffer = Buffer.from('客户统计导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', `attachment; filename=customer_statistics_${timeRange}.xlsx`)
  res.send(excelBuffer)
})

// 导出服务统计
app.get('/api/statistics/services/export', (req, res) => {
  const { timeRange, format } = req.query

  const excelBuffer = Buffer.from('服务统计导出文件内容')

  res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
  res.setHeader('Content-Disposition', `attachment; filename=service_statistics_${timeRange}.xlsx`)
  res.send(excelBuffer)
})

// 统计分析相关接口
// 获取地区统计数据
app.get('/api/statistics/regions', (req, res) => {
  const { timeRange, sortBy, sortOrder, limit } = req.query

  res.json({
    code: 200,
    message: '获取地区统计成功',
    data: [
      {
        rank: 1,
        region: '朝阳区',
        description: '北京市朝阳区',
        orders: 0,
        orderTrend: 0,
        revenue: 0,
        revenueTrend: 0,
        avgOrderValue: 0,
        satisfaction: 0,
        growth: 0
      },
      {
        rank: 2,
        region: '海淀区',
        description: '北京市海淀区',
        orders: 0,
        orderTrend: 0,
        revenue: 0,
        revenueTrend: 0,
        avgOrderValue: 0,
        satisfaction: 0,
        growth: 0
      }
    ]
  })
})

// 获取时间段分析数据
app.get('/api/statistics/time-analysis', (req, res) => {
  const { timeRange, metric, granularity } = req.query

  // 直接返回数组格式，与前端期望一致
  res.json({
    code: 200,
    message: '获取时间分析数据成功',
    data: [
      { time: '00-06', orders: 0, revenue: 0, percentage: 0 },
      { time: '06-12', orders: 0, revenue: 0, percentage: 0 },
      { time: '12-18', orders: 0, revenue: 0, percentage: 0 },
      { time: '18-24', orders: 0, revenue: 0, percentage: 0 }
    ]
  })
})

// 获取服务类型分析数据
app.get('/api/statistics/service-types', (req, res) => {
  const { timeRange, metric } = req.query

  res.json({
    code: 200,
    message: '获取服务类型分析成功',
    data: [
      {
        type: 'clothes',
        name: '衣物洗护',
        orders: 0,
        revenue: 0,
        percentage: 0,
        growth: 0,
        satisfaction: 0,
        icon: '👔'
      },
      {
        type: 'shoes',
        name: '鞋类清洗',
        orders: 0,
        revenue: 0,
        percentage: 0,
        growth: 0,
        satisfaction: 0,
        icon: '👟'
      },
      {
        type: 'pets',
        name: '宠物清洗',
        orders: 0,
        revenue: 0,
        percentage: 0,
        growth: 0,
        satisfaction: 0,
        icon: '🐕'
      },
      {
        type: 'bags',
        name: '包包清洗',
        orders: 0,
        revenue: 0,
        percentage: 0,
        growth: 0,
        satisfaction: 0,
        icon: '👜'
      },
      {
        type: 'bedding',
        name: '被子清洗',
        orders: 0,
        revenue: 0,
        percentage: 0,
        growth: 0,
        satisfaction: 0,
        icon: '🛏️'
      },
      {
        type: 'car',
        name: '洗车服务',
        orders: 0,
        revenue: 0,
        percentage: 0,
        growth: 0,
        satisfaction: 0,
        icon: '🚗'
      }
    ]
  })
})

// 获取客户满意度统计
app.get('/api/statistics/satisfaction', (req, res) => {
  const { timeRange, groupBy, serviceType, region } = req.query

  res.json({
    code: 200,
    message: '获取客户满意度统计成功',
    data: {
      timeRange: timeRange,
      groupBy: groupBy,
      serviceType: serviceType,
      region: region,
      averageRating: 0,
      ratingDistribution: [],
      chartData: [],
      trends: []
    }
  })
})

// 获取运营效率统计
app.get('/api/statistics/operation-efficiency', (req, res) => {
  const { timeRange, metric } = req.query

  res.json({
    code: 200,
    message: '获取运营效率统计成功',
    data: {
      timeRange: timeRange,
      metric: metric,
      efficiency: {
        processingTime: 0,
        responseTime: 0,
        completionRate: 0,
        qualityScore: 0
      },
      chartData: [],
      benchmarks: []
    }
  })
})

// 获取竞争分析数据
app.get('/api/statistics/competitive-analysis', (req, res) => {
  const { timeRange, region, serviceType } = req.query

  res.json({
    code: 200,
    message: '获取竞争分析数据成功',
    data: {
      timeRange: timeRange,
      region: region,
      serviceType: serviceType,
      marketShare: 0,
      competitorCount: 0,
      priceComparison: [],
      strengthsWeaknesses: {
        strengths: [],
        weaknesses: [],
        opportunities: [],
        threats: []
      }
    }
  })
})

// 获取实时数据
app.get('/api/statistics/realtime', (req, res) => {
  res.json({
    code: 200,
    message: '获取实时数据成功',
    data: {
      onlineUsers: 0,
      activeOrders: 0,
      todayRevenue: 0,
      systemLoad: 0,
      lastUpdate: new Date().toISOString()
    }
  })
})

// 获取预测数据
app.get('/api/statistics/forecast', (req, res) => {
  const { metric, period, model } = req.query

  res.json({
    code: 200,
    message: '获取预测数据成功',
    data: {
      metric: metric,
      period: parseInt(period),
      model: model,
      forecast: [],
      confidence: 0,
      accuracy: 0,
      lastTrainingDate: new Date().toISOString()
    }
  })
})

// 批量操作订单
app.post('/api/orders/batch', (req, res) => {
  const { ids, action } = req.body

  res.json({
    code: 200,
    message: '批量操作成功',
    data: {
      successCount: ids.length,
      failedCount: 0,
      action: action
    }
  })
})

// 获取订单列表
app.get('/api/orders', (req, res) => {
  const { page = 0, size = 10, status, keyword, startDate, endDate } = req.query

  res.json({
    code: 200,
    message: '获取订单列表成功',
    data: {
      records: [],
      total: 0,
      page: parseInt(page),
      size: parseInt(size)
    }
  })
})

// 获取订单详情
app.get('/api/orders/:id', (req, res) => {
  const { id } = req.params

  res.json({
    code: 200,
    message: '获取订单详情成功',
    data: {
      id: parseInt(id),
      orderNo: `LD${Date.now()}`,
      status: 'pending',
      createTime: new Date().toISOString()
    }
  })
})

// 更新订单状态
app.put('/api/orders/:id/status', (req, res) => {
  const { id } = req.params
  const { status, remark } = req.body

  res.json({
    code: 200,
    message: '订单状态更新成功',
    data: {
      id: parseInt(id),
      status: status,
      remark: remark,
      updateTime: new Date().toISOString()
    }
  })
})



// ==================== 银行卡绑定管理 ====================

// 获取银行卡绑定状态
app.get('/api/bankcard/status', (req, res) => {
  const merchantId = 'merchant_001' // 实际应从token中获取
  const bankCard = bankCardMap.get(merchantId)

  res.json({
    code: 200,
    message: '查询成功',
    data: {
      isBound: !!bankCard,
      bankCard: bankCard ? {
        id: bankCard.id,
        bankName: bankCard.bankName,
        cardNumber: bankCard.cardNumber.replace(/(\d{4})\d{8}(\d{4})/, '$1****$2'), // 脱敏处理
        cardType: bankCard.cardType,
        bindTime: bankCard.bindTime,
        status: bankCard.status
      } : null,
      idCardVerified: !!idCardVerificationMap.get(merchantId)
    }
  })
})

// 身份证实名认证
app.post('/api/bankcard/verify-idcard', (req, res) => {
  const { idCardNumber, realName, idCardFront, idCardBack } = req.body
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 模拟身份证验证（真实环境需要调用公安部接口）
  if (!idCardNumber || !realName || !idCardFront || !idCardBack) {
    res.json({
      code: 400,
      message: '身份证信息不完整',
      data: null
    })
    return
  }

  // 模拟验证成功
  const verificationData = {
    merchantId: merchantId,
    idCardNumber: idCardNumber,
    realName: realName,
    idCardFront: idCardFront,
    idCardBack: idCardBack,
    verifyTime: new Date().toISOString(),
    status: 'verified'
  }

  idCardVerificationMap.set(merchantId, verificationData)

  res.json({
    code: 200,
    message: '身份证验证成功',
    data: {
      verified: true,
      realName: realName,
      verifyTime: verificationData.verifyTime
    }
  })
})

// 绑定银行卡
app.post('/api/bankcard/bind', (req, res) => {
  const { cardNumber, bankName, cardType, holderName, phoneNumber, smsCode } = req.body
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 检查身份证是否已验证
  const idCardVerification = idCardVerificationMap.get(merchantId)
  if (!idCardVerification) {
    res.json({
      code: 403,
      message: '请先完成身份证实名认证',
      data: null
    })
    return
  }

  // 验证持卡人姓名是否与身份证一致
  if (holderName !== idCardVerification.realName) {
    res.json({
      code: 400,
      message: '持卡人姓名与身份证姓名不一致',
      data: null
    })
    return
  }

  // 模拟银行卡验证（真实环境需要调用银行接口）
  if (!cardNumber || !bankName || !holderName || !phoneNumber || !smsCode) {
    res.json({
      code: 400,
      message: '银行卡信息不完整',
      data: null
    })
    return
  }

  // 模拟短信验证码验证
  if (smsCode !== '123456') {
    res.json({
      code: 400,
      message: '短信验证码错误',
      data: null
    })
    return
  }

  // 检查是否已绑定银行卡
  if (bankCardMap.has(merchantId)) {
    res.json({
      code: 400,
      message: '您已绑定银行卡，如需更换请先解绑',
      data: null
    })
    return
  }

  // 绑定银行卡
  const bankCardData = {
    id: `card_${Date.now()}`,
    merchantId: merchantId,
    cardNumber: cardNumber,
    bankName: bankName,
    cardType: cardType,
    holderName: holderName,
    phoneNumber: phoneNumber,
    bindTime: new Date().toISOString(),
    status: 'active'
  }

  bankCardMap.set(merchantId, bankCardData)

  res.json({
    code: 200,
    message: '银行卡绑定成功',
    data: {
      cardId: bankCardData.id,
      bankName: bankName,
      cardNumber: cardNumber.replace(/(\d{4})\d{8}(\d{4})/, '$1****$2'),
      bindTime: bankCardData.bindTime
    }
  })
})

// 发送短信验证码
app.post('/api/bankcard/send-sms', (req, res) => {
  const { phoneNumber, type } = req.body // type: bind, unbind, payment

  // 模拟发送短信验证码
  console.log(`发送短信验证码到 ${phoneNumber}，类型: ${type}，验证码: 123456`)

  res.json({
    code: 200,
    message: '短信验证码发送成功',
    data: {
      expireTime: new Date(Date.now() + 5 * 60 * 1000).toISOString() // 5分钟过期
    }
  })
})

// ==================== 退店申请管理 ====================

// 检查退店条件
app.get('/api/store-closure/check-conditions', (req, res) => {
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 检查各项退店条件
  const conditions = {
    // 1. 检查在途订单
    hasOngoingOrders: checkOngoingOrders(merchantId),

    // 2. 检查一个月内纠纷
    hasRecentDisputes: checkRecentDisputes(merchantId),

    // 3. 检查是否有新订单产生
    hasNewOrders: checkNewOrders(merchantId),

    // 4. 检查未完成订单
    hasIncompleteOrders: checkIncompleteOrders(merchantId),

    // 5. 检查账户状态
    accountStatus: checkAccountStatus(merchantId),

    // 6. 检查罚款记录
    hasPenalties: checkPenalties(merchantId),

    // 7. 检查其他服务
    hasOtherServices: checkOtherServices(merchantId)
  }

  // 计算是否满足退店条件
  const canApplyForClosure = !conditions.hasOngoingOrders &&
                            !conditions.hasRecentDisputes &&
                            !conditions.hasNewOrders &&
                            !conditions.hasIncompleteOrders &&
                            conditions.accountStatus === 'normal' &&
                            !conditions.hasPenalties &&
                            !conditions.hasOtherServices

  res.json({
    code: 200,
    message: '退店条件检查完成',
    data: {
      canApplyForClosure: canApplyForClosure,
      conditions: {
        ongoingOrders: {
          passed: !conditions.hasOngoingOrders,
          description: '无在途订单',
          details: conditions.hasOngoingOrders ? '存在未完成的在途订单' : '所有订单已完成'
        },
        recentDisputes: {
          passed: !conditions.hasRecentDisputes,
          description: '一个月内无纠纷',
          details: conditions.hasRecentDisputes ? '一个月内存在纠纷记录' : '一个月内无纠纷记录'
        },
        newOrders: {
          passed: !conditions.hasNewOrders,
          description: '无新订单产生',
          details: conditions.hasNewOrders ? '近期有新订单产生' : '无新订单产生'
        },
        incompleteOrders: {
          passed: !conditions.hasIncompleteOrders,
          description: '所有订单已完成',
          details: conditions.hasIncompleteOrders ? '存在未完成订单' : '所有订单已完成'
        },
        accountStatus: {
          passed: conditions.accountStatus === 'normal',
          description: '账户状态正常',
          details: conditions.accountStatus === 'normal' ? '账户状态正常' : `账户状态异常: ${conditions.accountStatus}`
        },
        penalties: {
          passed: !conditions.hasPenalties,
          description: '无罚款记录',
          details: conditions.hasPenalties ? '存在未处理的罚款' : '无罚款记录'
        },
        otherServices: {
          passed: !conditions.hasOtherServices,
          description: '无其他服务',
          details: conditions.hasOtherServices ? '存在其他未关闭的服务' : '无其他服务'
        }
      }
    }
  })
})

// 提交退店申请
app.post('/api/store-closure/apply', (req, res) => {
  const { reason, contactPhone, emergencyContact } = req.body
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 再次检查退店条件
  const conditions = checkAllClosureConditions(merchantId)
  if (!conditions.canApply) {
    res.json({
      code: 400,
      message: '不满足退店条件，无法提交申请',
      data: {
        failedConditions: conditions.failedConditions
      }
    })
    return
  }

  // 创建退店申请
  const applicationId = `SC${Date.now()}`
  const application = {
    id: applicationId,
    merchantId: merchantId,
    reason: reason,
    contactPhone: contactPhone,
    emergencyContact: emergencyContact,
    status: 'pending', // pending: 待审核, approved: 已同意, rejected: 已拒绝, completed: 已完成
    applyTime: new Date().toISOString(),
    conditions: conditions.conditionsSnapshot,
    depositAmount: calculateDepositRefund(merchantId),
    reviewNotes: '',
    reviewTime: null,
    completionTime: null
  }

  storeClosureApplicationsMap.set(applicationId, application)

  res.json({
    code: 200,
    message: '退店申请提交成功，请等待后台审核',
    data: {
      applicationId: applicationId,
      status: 'pending',
      applyTime: application.applyTime,
      estimatedReviewTime: new Date(Date.now() + 3 * 24 * 60 * 60 * 1000).toISOString(), // 3天后
      depositAmount: application.depositAmount
    }
  })
})

// 获取退店申请状态
app.get('/api/store-closure/status', (req, res) => {
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 查找该商户的退店申请
  let application = null
  for (const [id, app] of storeClosureApplicationsMap) {
    if (app.merchantId === merchantId) {
      application = app
      break
    }
  }

  if (!application) {
    res.json({
      code: 200,
      message: '查询成功',
      data: {
        hasApplication: false,
        application: null
      }
    })
    return
  }

  res.json({
    code: 200,
    message: '查询成功',
    data: {
      hasApplication: true,
      application: {
        id: application.id,
        status: application.status,
        reason: application.reason,
        applyTime: application.applyTime,
        reviewTime: application.reviewTime,
        completionTime: application.completionTime,
        depositAmount: application.depositAmount,
        reviewNotes: application.reviewNotes
      }
    }
  })
})

// 取消退店申请
app.post('/api/store-closure/cancel', (req, res) => {
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 查找该商户的退店申请
  let applicationId = null
  for (const [id, app] of storeClosureApplicationsMap) {
    if (app.merchantId === merchantId && app.status === 'pending') {
      applicationId = id
      break
    }
  }

  if (!applicationId) {
    res.json({
      code: 400,
      message: '没有可取消的退店申请',
      data: null
    })
    return
  }

  // 删除申请
  storeClosureApplicationsMap.delete(applicationId)

  res.json({
    code: 200,
    message: '退店申请已取消',
    data: null
  })
})

// ==================== 退店条件检查辅助函数 ====================

// 检查在途订单
function checkOngoingOrders(merchantId) {
  // 模拟检查在途订单
  // 在真实环境中，这里会查询数据库中状态为 'processing', 'shipping', 'delivering' 等的订单
  const ongoingOrders = ordersMap.get(merchantId) || []
  return ongoingOrders.some(order => ['processing', 'shipping', 'delivering'].includes(order.status))
}

// 检查一个月内纠纷
function checkRecentDisputes(merchantId) {
  // 模拟检查一个月内的纠纷记录
  const disputes = disputesMap.get(merchantId) || []
  const oneMonthAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000)

  return disputes.some(dispute => {
    const disputeDate = new Date(dispute.createTime)
    return disputeDate > oneMonthAgo
  })
}

// 检查新订单
function checkNewOrders(merchantId) {
  // 模拟检查最近是否有新订单
  const orders = ordersMap.get(merchantId) || []
  const threeDaysAgo = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000)

  return orders.some(order => {
    const orderDate = new Date(order.createTime)
    return orderDate > threeDaysAgo
  })
}

// 检查未完成订单
function checkIncompleteOrders(merchantId) {
  // 模拟检查未完成的订单
  const orders = ordersMap.get(merchantId) || []
  return orders.some(order => !['completed', 'cancelled'].includes(order.status))
}

// 检查账户状态
function checkAccountStatus(merchantId) {
  // 模拟检查账户状态
  // 在真实环境中，这里会查询商户账户的状态
  return 'normal' // normal, frozen, suspended, banned
}

// 检查罚款记录
function checkPenalties(merchantId) {
  // 模拟检查未处理的罚款
  const penalties = penaltiesMap.get(merchantId) || []
  return penalties.some(penalty => penalty.status === 'unpaid')
}

// 检查其他服务
function checkOtherServices(merchantId) {
  // 模拟检查其他未关闭的服务
  const services = otherServicesMap.get(merchantId) || []
  return services.some(service => service.status === 'active')
}

// 综合检查所有退店条件
function checkAllClosureConditions(merchantId) {
  const hasOngoingOrders = checkOngoingOrders(merchantId)
  const hasRecentDisputes = checkRecentDisputes(merchantId)
  const hasNewOrders = checkNewOrders(merchantId)
  const hasIncompleteOrders = checkIncompleteOrders(merchantId)
  const accountStatus = checkAccountStatus(merchantId)
  const hasPenalties = checkPenalties(merchantId)
  const hasOtherServices = checkOtherServices(merchantId)

  const canApply = !hasOngoingOrders &&
                   !hasRecentDisputes &&
                   !hasNewOrders &&
                   !hasIncompleteOrders &&
                   accountStatus === 'normal' &&
                   !hasPenalties &&
                   !hasOtherServices

  const failedConditions = []
  if (hasOngoingOrders) failedConditions.push('存在在途订单')
  if (hasRecentDisputes) failedConditions.push('一个月内有纠纷记录')
  if (hasNewOrders) failedConditions.push('近期有新订单产生')
  if (hasIncompleteOrders) failedConditions.push('存在未完成订单')
  if (accountStatus !== 'normal') failedConditions.push('账户状态异常')
  if (hasPenalties) failedConditions.push('存在未处理罚款')
  if (hasOtherServices) failedConditions.push('存在其他未关闭服务')

  return {
    canApply: canApply,
    failedConditions: failedConditions,
    conditionsSnapshot: {
      hasOngoingOrders,
      hasRecentDisputes,
      hasNewOrders,
      hasIncompleteOrders,
      accountStatus,
      hasPenalties,
      hasOtherServices,
      checkTime: new Date().toISOString()
    }
  }
}

// 计算保证金退还金额
function calculateDepositRefund(merchantId) {
  // 模拟计算保证金退还金额
  // 在真实环境中，这里会查询商户的保证金余额
  const bankCard = bankCardMap.get(merchantId)
  if (!bankCard) return 0

  // 假设保证金总额为5000元
  const totalDeposit = 5000
  const penalties = penaltiesMap.get(merchantId) || []
  const totalPenalties = penalties.reduce((sum, penalty) => sum + penalty.amount, 0)

  return Math.max(0, totalDeposit - totalPenalties)
}

// 获取服务图标
function getServiceIcon(type) {
  const iconMap = {
    'laundry': '👔',
    'shoes': '👟',
    'pet': '🐕',
    'bag': '👜',
    'bedding': '🛏️',
    'car': '🚗',
    'home_cleaning': '🏠',
    'plumbing': '🔧'
  }
  return iconMap[type] || '🔧'
}

// 根据保证金金额获取风险等级
function getRiskLevel(deposit) {
  if (deposit <= 500) return 'low'
  if (deposit <= 1000) return 'medium'
  return 'high'
}

// 获取服务要求
function getServiceRequirements(type) {
  const requirementsMap = {
    'laundry': [
      '具备基础洗护技能',
      '拥有洗护设备',
      '了解面料特性'
    ],
    'shoes': [
      '掌握鞋类清洗技术',
      '具备专业清洗工具',
      '了解不同材质处理方法'
    ],
    'pet': [
      '具备宠物用品清洗经验',
      '了解宠物安全要求',
      '掌握消毒杀菌技术'
    ],
    'bag': [
      '具备皮具护理技能',
      '了解不同材质特性',
      '掌握修复技术'
    ],
    'bedding': [
      '具备大件清洗能力',
      '拥有专业洗护设备',
      '掌握除螨杀菌技术'
    ],
    'car': [
      '具备汽车美容资质',
      '拥有专业清洗设备',
      '了解汽车保养知识'
    ],
    'home_cleaning': [
      '具备家政服务经验',
      '拥有清洁工具设备',
      '了解安全操作规范'
    ],
    'plumbing': [
      '具备管道维修技能',
      '拥有专业疏通工具',
      '了解管道结构原理'
    ]
  }
  return requirementsMap[type] || ['具备相关技能', '了解服务标准']
}

// 获取最大服务数量
function getMaxServices(type) {
  const maxServicesMap = {
    'laundry': 10,
    'shoes': 5,
    'pet': 8,
    'bag': 6,
    'bedding': 7,
    'car': 15,
    'home_cleaning': 20,
    'plumbing': 12
  }
  return maxServicesMap[type] || 10
}

// ==================== 风控提醒管理 ====================

// 获取风控提醒
app.get('/api/risk/alerts', (req, res) => {
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 模拟风控数据
  const riskData = {
    refundRate: 18.5, // 退款率 18.5%
    responseTime: 25, // 平均响应时间 25分钟
    orderCount: 156, // 总订单数
    refundCount: 29, // 退款订单数
    avgResponseTime: 25, // 平均响应时间（分钟）
    lastUpdateTime: new Date().toISOString()
  }

  // 生成风控提醒
  const alerts = []

  // 退款率检查（超过15%提醒）
  if (riskData.refundRate > 15) {
    alerts.push({
      id: 'refund_rate_high',
      type: 'warning',
      level: riskData.refundRate > 20 ? 'high' : 'medium',
      title: '退款率偏高提醒',
      message: `当前退款率为 ${riskData.refundRate}%，超过平台标准（15%），请关注服务质量`,
      suggestion: '建议：1. 检查服务流程 2. 提升服务质量 3. 加强与客户沟通',
      createTime: new Date().toISOString(),
      data: {
        currentRate: riskData.refundRate,
        standardRate: 15,
        totalOrders: riskData.orderCount,
        refundOrders: riskData.refundCount
      }
    })
  }

  // 响应时间检查（超过20分钟提醒）
  if (riskData.responseTime > 20) {
    alerts.push({
      id: 'response_time_slow',
      type: 'warning',
      level: riskData.responseTime > 30 ? 'high' : 'medium',
      title: '响应时间提醒',
      message: `平均响应时间为 ${riskData.responseTime} 分钟，超过平台标准（20分钟），请及时处理订单`,
      suggestion: '建议：1. 优化接单流程 2. 增加人手配置 3. 设置自动提醒',
      createTime: new Date().toISOString(),
      data: {
        currentTime: riskData.responseTime,
        standardTime: 20,
        unit: 'minutes'
      }
    })
  }

  // 如果没有风险，添加正常状态
  if (alerts.length === 0) {
    alerts.push({
      id: 'all_normal',
      type: 'success',
      level: 'low',
      title: '风控状态正常',
      message: '当前各项指标均在正常范围内，请继续保持',
      suggestion: '继续保持优质服务，关注客户反馈',
      createTime: new Date().toISOString(),
      data: {
        refundRate: riskData.refundRate,
        responseTime: riskData.responseTime
      }
    })
  }

  res.json({
    code: 200,
    message: '获取风控提醒成功',
    data: {
      alerts: alerts,
      summary: {
        totalAlerts: alerts.length,
        highRiskCount: alerts.filter(a => a.level === 'high').length,
        mediumRiskCount: alerts.filter(a => a.level === 'medium').length,
        lowRiskCount: alerts.filter(a => a.level === 'low').length
      },
      riskData: riskData
    }
  })
})

// 标记风控提醒已读
app.post('/api/risk/alerts/:alertId/read', (req, res) => {
  const { alertId } = req.params

  console.log(`标记风控提醒已读: ${alertId}`)

  res.json({
    code: 200,
    message: '标记已读成功',
    data: {
      alertId: alertId,
      readTime: new Date().toISOString()
    }
  })
})

// 获取风控统计数据
app.get('/api/risk/statistics', (req, res) => {
  const merchantId = 'merchant_001' // 实际应从token中获取

  // 模拟风控统计数据
  const statistics = {
    refundRate: {
      current: 18.5,
      lastMonth: 16.2,
      trend: 'up', // up, down, stable
      standard: 15
    },
    responseTime: {
      current: 25,
      lastMonth: 22,
      trend: 'up',
      standard: 20,
      unit: 'minutes'
    },
    customerSatisfaction: {
      current: 4.2,
      lastMonth: 4.5,
      trend: 'down',
      standard: 4.0,
      unit: 'stars'
    },
    orderCompletion: {
      current: 94.5,
      lastMonth: 96.1,
      trend: 'down',
      standard: 95,
      unit: 'percent'
    }
  }

  res.json({
    code: 200,
    message: '获取风控统计成功',
    data: statistics
  })
})

// ==================== 仪表板统计数据API ====================

// 获取时间段分析数据
app.get('/api/dashboard/time-analysis', (req, res) => {
  const { type = 'today' } = req.query

  // 真实环境中应该从数据库查询
  // 目前返回0数据，等待真实商家入驻
  const timeData = {
    today: {
      times: ['00-06', '06-12', '12-18', '18-24'],
      values: [0, 0, 0, 0]
    },
    week: {
      times: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      values: [0, 0, 0, 0, 0, 0, 0]
    },
    month: {
      times: ['第1周', '第2周', '第3周', '第4周'],
      values: [0, 0, 0, 0]
    }
  }

  res.json({
    code: 200,
    message: '获取时间段分析数据成功',
    data: timeData[type] || timeData.today
  })
})

// 获取服务类型统计数据
app.get('/api/dashboard/service-stats', (req, res) => {
  const { type = 'orders' } = req.query

  // 真实环境中应该从数据库查询
  // 目前返回0数据，等待真实商家入驻
  const serviceData = {
    orders: [
      { value: 0, name: '洗衣服' },
      { value: 0, name: '洗鞋' },
      { value: 0, name: '洗包包' },
      { value: 0, name: '洗被子' },
      { value: 0, name: '洗车' },
      { value: 0, name: '上门清洗' }
    ],
    revenue: [
      { value: 0, name: '洗衣服' },
      { value: 0, name: '洗鞋' },
      { value: 0, name: '洗包包' },
      { value: 0, name: '洗被子' },
      { value: 0, name: '洗车' },
      { value: 0, name: '上门清洗' }
    ]
  }

  res.json({
    code: 200,
    message: '获取服务类型统计数据成功',
    data: serviceData[type] || serviceData.orders
  })
})

// 获取地区统计数据
app.get('/api/dashboard/region-stats', (req, res) => {
  const { type = 'orders' } = req.query

  // 真实环境中应该从数据库查询
  // 目前返回0数据，等待真实商家入驻
  const regionData = {
    orders: {
      regions: ['朝阳区', '海淀区', '西城区', '东城区', '丰台区', '其他'],
      values: [0, 0, 0, 0, 0, 0],
      list: [
        { name: '朝阳区', value: 0, unit: '单', percent: 0 },
        { name: '海淀区', value: 0, unit: '单', percent: 0 },
        { name: '西城区', value: 0, unit: '单', percent: 0 },
        { name: '东城区', value: 0, unit: '单', percent: 0 },
        { name: '丰台区', value: 0, unit: '单', percent: 0 },
        { name: '其他区域', value: 0, unit: '单', percent: 0 }
      ]
    },
    customers: {
      regions: ['朝阳区', '海淀区', '西城区', '东城区', '丰台区', '其他'],
      values: [0, 0, 0, 0, 0, 0],
      list: [
        { name: '朝阳区', value: 0, unit: '人', percent: 0 },
        { name: '海淀区', value: 0, unit: '人', percent: 0 },
        { name: '西城区', value: 0, unit: '人', percent: 0 },
        { name: '东城区', value: 0, unit: '人', percent: 0 },
        { name: '丰台区', value: 0, unit: '人', percent: 0 },
        { name: '其他区域', value: 0, unit: '人', percent: 0 }
      ]
    },
    revenue: {
      regions: ['朝阳区', '海淀区', '西城区', '东城区', '丰台区', '其他'],
      values: [0, 0, 0, 0, 0, 0],
      list: [
        { name: '朝阳区', value: 0, unit: '元', percent: 0 },
        { name: '海淀区', value: 0, unit: '元', percent: 0 },
        { name: '西城区', value: 0, unit: '元', percent: 0 },
        { name: '东城区', value: 0, unit: '元', percent: 0 },
        { name: '丰台区', value: 0, unit: '元', percent: 0 },
        { name: '其他区域', value: 0, unit: '元', percent: 0 }
      ]
    }
  }

  res.json({
    code: 200,
    message: '获取地区统计数据成功',
    data: regionData[type] || regionData.orders
  })
})

// 获取仪表板概览数据
app.get('/api/dashboard/overview', (req, res) => {
  // 真实环境中应该从数据库查询
  // 目前返回0数据，等待真实商家入驻
  res.json({
    code: 200,
    message: '获取仪表板概览数据成功',
    data: {
      todayRevenue: 0,
      todayOrders: 0,
      totalCustomers: 0,
      averageRating: 0,
      pendingOrders: 0,
      completedOrders: 0,
      totalRevenue: 0,
      monthlyGrowth: 0,
      customerGrowth: 0,
      revenueGrowth: 0
    }
  })
})

// 通用错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err)
  res.status(500).json({
    code: 500,
    message: '服务器内部错误',
    data: null
  })
})

// 404处理
app.use((req, res) => {
  res.status(404).json({
    code: 404,
    message: '接口不存在',
    data: null
  })
})

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 测试后端服务器启动成功`)
  console.log(`📍 服务地址: http://localhost:${PORT}`)
  console.log(`🔗 健康检查: http://localhost:${PORT}/api/health`)
  console.log(`📋 可用测试账号:`)
  testAccounts.forEach((account, index) => {
    console.log(`   ${index + 1}. ${account.username} / ${account.password} (${account.userInfo.name})`)
  })
  console.log(`⏰ 启动时间: ${new Date().toISOString()}`)
})

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('收到SIGTERM信号，正在关闭服务器...')
  process.exit(0)
})

process.on('SIGINT', () => {
  console.log('收到SIGINT信号，正在关闭服务器...')
  process.exit(0)
})
